Hey visitors! If you’re a beginner in WordPress and WP-CLI development, then you should check out my dear friend Bhargav’s Youtube channel! @BuntyWP

How to use the preview device within the Gutenberg editor?

The Gutenberg editor offers 3 devices for preview:

  • Desktop
  • Tablet
  • and Mobile.

For responsive blocks, you might want them to appear a certain way based on the device type. How do you do that?

Let’s set a simple goal for the sake of learning.

Goal: Create a simple text block which changes its background color based on the device type.

  • Desktop – #83BFFF color
  • Tablet – #FF6347 color
  • Mobile – #7BDCB5 color

Note: In this post, we will be only focusing on the editor UI. On the front-end, you will obviously use CSS media queries.

Create a block

import './editor.scss';

export default function Edit() {
    return (
        <div>
            <h1>Welcome, user!</h1>
        </div>
    );
}Code language: JavaScript (javascript)

The CSS:

.device-wrapper {
    text-align: center;
    border: 4px solid #141414;
}Code language: CSS (css)

Get the device type

import { useBlockProps } from '@wordpress/block-editor';
import { useSelect } from "@wordpress/data";
import './editor.scss';

export default function Edit() {
    const { deviceType } = useSelect( select => {
        const { __experimentalGetPreviewDeviceType } = select( 'core/edit-post' );
    
        return {
            deviceType: __experimentalGetPreviewDeviceType(),
        }
    }, [] );

    const blockProps = useBlockProps( {
        className: `device-wrapper device-wrapper--${ deviceType }`
    } );

    return (
        <div { ...blockProps }>
            <h1>Welcome, user!</h1>
        </div>
    );
}
Code language: JavaScript (javascript)

The CSS:

.device-wrapper {
    text-align: center;
    border: 4px solid #141414;
}

.device-wrapper--Desktop {
    text-align: center;
    border: 4px solid #141414;
    background-color: #83BFFF;
}

.device-wrapper--Tablet {
    text-align: center;
    border: 4px solid #141414;
    background-color: #FF6347;
}

.device-wrapper--Mobile {
    text-align: center;
    border: 4px solid #141414;
    background-color: #7BDCB5;
}

Code language: CSS (css)

The final result



Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

Powered by WordPress