Aslam Doctor

A little trick to exclude blocks from innerBlocks component

With the help of innerBlocks component, you can nest all the other existing blocks inside the current block. If you want to define the set of blocks that should be allowed in your InnerBlock, it provides a property called allowedBlocks. In that you can provide an array containing names of all the blocks that should be allowed to be added inside innerBlock.

But innerBlock doesn’t have a property that can allow you to define a list of blocks that should not be added to it. To fix that, here is a little trick that I came up with. In this, we are creating an array of all the existing blocks and then removing the ones from it that we want to exclude. Now when we pass this list to the allowedBlocks property, it will allow you to add all the blocks except the ones that got removed from the list.

1. Import getBlockTypes first

The getBlockTypes() method gives you the list of names for all the blocks registered to be used by the block editor (including core blocks). Here we are also extracting metadata from block.json to retrieve the block name which will be used in the next step. e.g. my-block/carousel

import metadata from "./block.json";
import { getBlockTypes } from "@wordpress/blocks";

2. Create a list of allowed blocks

Here adding metadata.name to the array will exclude the current block from being added to itself. You can also add more block names to this array if you want them to be excluded.

const ALLOWED_BLOCKS = getBlockTypes()
		.map((block) => block.name)
		.filter((blockName) => [metadata.name].indexOf(blockName) === -1);

3. Add it to the allowedBlocks property

And finally, pass the ALLOWED_BLOCKS constant to the InnerBlocks component under allowedBlocks property.

<InnerBlocks allowedBlocks={ALLOWED_BLOCKS} />