I have a custom block called Custom Card
that takes an InnerBlock
as a child. The purpose of this is because I want to format the content within the Custom Card
a very specific way.
The Custom Card
has three allowed blocks:
core/quote
core/video
core/image
The problem I've run into, is that after a user selects a block they can continue to add more blocks to the same Card. I want to limit the card to allow them to select one of the three options they have available. What is some ways I can go about doing this?
I have a custom block called Custom Card
that takes an InnerBlock
as a child. The purpose of this is because I want to format the content within the Custom Card
a very specific way.
The Custom Card
has three allowed blocks:
core/quote
core/video
core/image
The problem I've run into, is that after a user selects a block they can continue to add more blocks to the same Card. I want to limit the card to allow them to select one of the three options they have available. What is some ways I can go about doing this?
Share Improve this question asked Oct 11, 2019 at 21:14 ZacharyZachary 1581 silver badge9 bronze badges2 Answers
Reset to default 2Here is a simple solution to this problem I've implemented using the renderAppender prop, inspired by Welcher's comment above and this post over on Stack.
<InnerBlocks
renderAppender={() => {
const blocks = select('core/editor').getBlocks();
const block = find(blocks, ['name', 'NAME_OF_YOUR_BLOCK']);
// don't return appender if there's one or more blocks:
if (block && block.innerBlocks.length > 0) return null;
// otherwise, return default appender
return (<InnerBlocks.DefaultBlockAppender />);
}}
/>
Note: This example is using lodash find function to get the block I'm targeting. There may be a better way to do this, but for now it does the job.
Also, be sure to import the select
function. E.g.
import { select } from '@wordpress/data';
The only way to do this at the moment is by using the renderAppender
prop onInnerBlocks
. This prop is only available in the Gutenberg plugin until WordPress 5.3 is released. The theory would be to use state in each CustomCard
to track if there has been a block added, then return false from the renderAppender
function so the user cannot insert more items.