How to Enable Gutenberg Block Previews

selective focus photography of person holding camera
Photo by Glenn Carstens-Peters on Unsplash

Block previews are an elusive pain-point and something I found hard to search for. As a result, this tutorial will show you how to create block previews for your block. The goal is to have an image or some block content show up when hovering over your block when adding it.

Gutenberg Block Preview Pane
Gutenberg Block Preview Pane

Block Initialization

When initializing your block, you can pass it some custom attribute values that will render the block in the preview pane. It’s important to set a description and use an example object which will pass attributes to your block.

For example, I have a block called wppp/slide-title that has several attributes to show off a slide title. What we’re essentially doing is short-circuiting the default attributes that are passed to our block. Here’s an example:

registerBlockType( 'wppp/slide-title', { title: __( 'Slide Title', 'wp-presenter-pro' ), // Block title. icon: <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5 4v3h5.5v12h3V7H19V4z"/><path fill="none" d="M0 0h24v24H0V0z"/></svg>, description: __( 'Use a slide title for your main title for the slide.', 'wp-presenter-pro' ), category: 'wp-presenter-pro', keywords: [ __( 'slide', 'wp-presenter-pro' ), __( 'title', 'wp-presenter-pro' ), ], edit: edit, save() {return null }, example: { attributes: { backgroundColor: '#000000', opacity: 0.8, padding: 30, textColor: '#FFFFFF', radius: 10, title: __( 'I am a slide title', 'wp-presenter-pro' ), }, }, } );
Code language: JavaScript (javascript)

Notice the example object above. This will be the object we use to short-circuit the default attributes passed to our block. We can essentially initialize the block with attributes and have a real preview based on our passed attributes.

Here’s the resulting preview:

Slide Title Block Preview
Slide Title Block Preview

Here’s another example I used for using my blockquote block.