Nifty Code #1: InnerBlocks

A new series I’m hoping to write this year, full of cool things you can do in the block editor or in JS in general. Some of this has been written about before, but I’ll also point out the use in projects I’m working on. 👩🏼‍💻

When writing the Recipe Block, I wanted to set out a “recipe post” framework, but not lock people into a fixed format. If you use it, you’ll see that inserting the block inserts a few blocks, including an image, title, ingredients, etc. But maybe you don’t have photos, or you want to add a video. If you try to insert a new block inside the “Recipe” container, you’ll see a restricted set of blocks, mostly things that would make sense – text, video, gallery… but not another Recipe block, or Latest Comments, etc.

This is thanks to a combination of the <InnerBlocks /> component, with the template & allowedBlocks props.

	template={ BLOCKS_TEMPLATE }
	templateLock={ false }
	allowedBlocks={ BLOCKS_ALLOWED }

The template allows you to define an array of blocks that will be pre-populated when the block is picked, along with pre-filling the attributes if you want. This is how I set up the initial template (you can see the source of BLOCKS_TEMPLATE on github).

Setting templateLock to false allows for adding and removing blocks.

Lastly, whitelist only specific blocks with allowedBlocks. This will restrict the blocks that can be added into your block “container” (users can still enter any block before or after your block). I’ve set this property to keep the recipe content organized. Check the list of BLOCKS_ALLOWED on github.

The best part of InnerBlocks is that you don’t need to do anything convoluted to save/display the content. In the block’s save function, you only need one line:

<InnerBlocks.Content />

This is really all it takes to create the Recipe block itself. In the next post I’ll talk about how I created the child blocks, which are the real functionality of the plugin.

Posted in:



No comments.

%d bloggers like this: