1

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?

2 Answers 2

2

Here 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';
2

The only way to do this at the moment is by using the renderAppenderprop 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.