How to add class names to nested blocks in Gutenberg

Nested blocks are some of the most versatile functionality I’ve seen come out of the Gutenberg project for WordPress. 

Instead of building all blocks components from scratch, you can use existing blocks and add them as nested blocks to your custom block. Read my tutorial for creating nested blocks in Gutenberg. 

One problem that arises is styling. Sure, you can get all specific with your CSS classes, but what if you have 4 different nested paragraph blocks, each with a different purpose? And what if each one needs to be styled differently?

Enter: class names!

Adding class names to nested blocks is easy. It all happens in the block template. 

The block template takes the name of the block, then an object with all the block properties and attributes, then an array of more nested blocks. In the block properties, you can set the className for the block. Here’s what that looks like:

const TEMPLATE = [
	[
		'core/paragraph', 
		{
			placeholder: 'Enter short recipe description...'
		}
	],
	[
		'core/paragraph',
		{
			placeholder: 'Enter ingredients...',
			className: 'nested-ingredients-p'
		}
	]
];

When the block is rendered in the editor or on the front-end, the class name will be added to the other class names for the block. You can use this new class name to style the block as you please. Easy peasy!

One Comment on “How to add class names to nested blocks in Gutenberg”

  1. Pingback: Update #99 Gutenberg Phase 2 Starting up, Finding Blocks and more. – Gutenberg Times

Leave a Reply

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