Build Multiple Gutenberg Blocks Using block.json | Custom SVG Icon For Blocks

In this blog, we will learn about how to build multiple custom Gutenberg blocks with the new convention of using block.json.

Create Files for Style and Script

Create a file called index.js and index.css in test-block directory.

Creating block.json file

Create a file called block.json and define all the properties.

{
	"apiVersion": 2,
	"name": "gutenberg-block-stater/test-block",
	"title": "Test Block",
	"category": "text",
	"icon": "star-filled",
	"description": "Test Block With Some Text",
	"keywords": [ "text", "message" ],
	"version": "1.0.3",
	"textdomain": "gutenberg-blocks-starter",
	"supports": {
		"align": true
	},
	"editorScript": "file:./index.js",
	"style": "file:./index.css"
}

Register Block Client side.

Place this code in index.js. If you are wondering how to use custom icons when building blocks with block.json , notice that we can override the icon value in JavaScript. This is useful when using block metadata.

import { registerBlockType } from '@wordpress/blocks';

import './index.scss';

registerBlockType( 'gutenberg-block-stater/test-block', {
	icon: {
		// Specifying a background color to appear with the icon e.g.: in the inserter.
		background: '#7e70af',
		// Specifying a color for the icon (optional: if not set, a readable color will be automatically defined)
		foreground: '#fff',
		// Specifying an icon for the block
		src: <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 13H5v-2h14v2z" /></svg>,
	} ,
	edit: () => ( <div className="test-block"> Hello World </div> ),
	save: () => ( <div className="test-block"> Hello World </div> )
} );

Register Block Server Side Using Metadata

When we register the block server-side and give the path to the root directory where block.json exists, it will automatically pick up the meta-data from block.json, and also include the styles and scripts automatically, when we specify the path of index.js and index.css in block.json editorScript and style pro properties prefixing it with file: The Style and script path should be relative to where block.json exists. Since in this case, block.json exists in the same folder as test-block, hence path will be file:./index.js"

namespace GutenbergBlockStarter;
function register_blocks() {
	register_block_type( GUTENBERG_BLOCK_STARTER_BUILD_DIR . '/test-block' );
	register_block_type( GUTENBERG_BLOCK_STARTER_BUILD_DIR . '/dos-and-donts' ); // This line is just an example, to register another block, if you had one.
}

add_action( 'init', __NAMESPACE__ . '\\register_blocks' );

Here is the code sample

Leave a Reply

%d bloggers like this: