Home / Block and Plugin Tutorials / Adding Gutenberg Block Previews to Existing Blocks – Block.json Edition

Adding Gutenberg Block Previews to Existing Blocks – Block.json Edition

Block.json Sample Code

Over at MediaRon.com, I wrote about how to enable Gutenberg block previews using a combination of PHP and JavaScript. Today, I’ll review the same concept, but use Block.json to accomplish the task.

What are block previews?

Block Editor Preview Example
Block Editor Preview Example

When you use the “+” inserter to add a block, a block preview is what pops up when you hover over a block. It gives the user a nice preview of what the block might look like when inserted into the block editor.

The block editor and attributes

When creating a block, you will inevitably run into attributes. These can also be called Block Options as attributes are usually married to actual options a user can configure for the block. For example, a background color attribute might correspond to a color picker that a user can use to customize the color.

The attribute types for Block.json are as follows:

  • null
  • boolean
  • object
  • array
  • string
  • integer
  • number

In most cases, you can get away with just using a boolean or string. You’d specify the type of attribute according to the data you need.

"attributes": {
	"show_copy": {
		"type": "boolean",
		"default": true
	},
	"show_permalink": {
		"type": "boolean",
		"default": true
	},
	"template": {
		"type": "string",
		"default": "light"
	}
},Code language: JSON / JSON with Comments (json)

Whenever you create an attribute for your block, you can give it a default. In the example above, I show three sample attributes that I created for one of my blocks.

For the show_copy attribute, for example, I have the type of boolean and a default value of true. Typically, true or false values are best left to ToggleControl components.

Block Editor Toggle Switches
Block Editor Toggle Switches

As a user uses the ToggleControl to change the value from true to false, the attribute is updated, and the user can update the post or page to “save” this attribute value. So switching the ToggleControl to the off position will change the show_copy attribute to a value of false.

Blocks can have a few of these attributes, while some can have a ton more.

Attributes and Previews

As shown in the previous section, you can declare attributes and their default values. With these default values, you can determine how a block will appear to the user when first inserted.

Sane defaults will give way to a better user experience, so you must balance intelligent defaults without overwhelming the user.

However, defaults don’t always show your block in the best light regarding previews. Some “extra” configuration is needed for that. What if there was a way to “override” your block defaults?

Enter the “example” parameter

In your block.json file, you can have an “example” parameter that will pass values to your attributes. Think of these as short-circuiting your block attributes by providing overrides.

"example": {
	"attributes": {
		"preview": true,
		"blockOnly": true,
		"share_text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque malesuada dui id nisi vulputate semper. Nam sagittis ac nulla id pharetra. Maecenas congue, tellus a blandit cursus, lorem dolor hendrerit erat, sed luctus arcu velit eget ligula.",
		"template": "purple-bliss",
		"enable_contextual_menu": true,
		"enable_copy_text": true,
		"enable_copy_tweet": true,
		"enable_copy_link": true,
		"enable_tweet_this": true,
		"maximum_width": 800,
		"maximum_width_unit": "px"
	}
},Code language: JSON / JSON with Comments (json)

In the above JSON snippet, I have several attributes that I am overriding in order to generate a preview. While I have set default attributes in a separate section, I can pass in my own custom values.

For example, the template attribute has a value of purple-bliss. I have four themes to choose from (in my case), so I pass it the one I want to use.

Another example is the share_text attribute. By default, my block’s share_text attribute is blank, but I can pass it some text to show in the preview.

Block Attribute Preview for QuotesDLX Plugin
Block Attribute Preview for QuotesDLX Plugin

Rendering an image instead

If your block doesn’t lend itself to “previews”, you can just use an image instead.

An example is with one of my plugins called WP Plugin Info Card.

Plugin Info Card

The first step is to create the image. I’ve found that the ideal image dimensions are: 680×720

Once you’ve created your image, you need to tell your block to display it as a preview. The easiest way is to use wp_localize_script.

In block.json, you can specify a filename for the script that loads in the block editor.

In this particular case, you’ll want to use a script handle instead.

Block.json Script Handles
Block.json Script Handles

In the above screenshot, I have a handle of quotes-dlx-block for the block.json editorScript parameter.

We’ll begin by enqueuing the block editor script and passing a preview parameter using wp_localize_script.

// Scripts.
wp_enqueue_script(
	'wp_plugin_info_card-cgb-block-js', // Handle.
	plugins_url( '/dist/main.js', dirname( __FILE__ ) ), // Block.build.js: We register the block here. Built with Webpack.
	array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ),
	WPPIC_VERSION,
	true // Enqueue the script in the footer.
);
wp_localize_script(
	'wp_plugin_info_card-cgb-block-js',
	'wppic',
	array(
		'rest_url'             => get_rest_url(),
		'query_preview'        => plugins_url( 'img/wp-query-preview.jpg', __FILE__ ),
		'wppic_preview'        => plugins_url( 'img/wp-pic-preview.jpg', __FILE__ ),
		'wppic_banner_default' => plugins_url( 'img/default-banner.png', __FILE__ ),
	)
);Code language: PHP (php)

In the above snippet, I enqueue the script, and pass in a global JS object called wppic.

We can then add an example parameter for the block preview.

Preview Attribute in Block.json
block.json Preview Parameter

Finally, we read in the preview attribute and return the image.

if ( preview ) {
	return(
		<>
			<img src={wppic.wppic_preview} />
		</>
	);
}Code language: JavaScript (javascript)

Conclusion

There are several ways to have block previews. You can wire up your block to show a default state, or use an image instead.

Please comment below if you have any questions and I can update this article.

Like this tutorial? There's more like it. Subscribe today!

Name(Required)

Ronald Huereca
By: Ronald Huereca
Published On: on August 17, 2022

Ronald Huereca founded DLX Plugins in 2022 with the goal of providing deluxe plugins available for download. Find out more about DLX Plugins, check out some tutorials, and check out our plugins.

Leave Your Valuable Feedback

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

Shopping Cart
  • Your cart is empty.
Scroll to Top