conditional layout based on if Innerblocks is not empty

I am not sure this is possible in a straightforward way.

You could add an attribute which checks if the block has innerBlocks. Then use it in save to render the wrapper or not. It works but it’s not a very clean solution:

const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
const { useSelect } = wp.data;
const { useEffect } = wp.element;

registerBlockType("my-plugin/my-block", {
    title: __("My block"),
    icon: "carrot",
    category: "common",
    attributes: {
        innerBlocks_length: {
            type: "number",
            default: 0
        }
    },
    edit: props => {
        const { className, clientId, setAttributes } = props;
        const { innerBlocks_length } = useSelect(select => ({
            innerBlocks_length: select("core/block-editor").getBlockCount(clientId)
        }));

        useEffect(() => {
            setAttributes({ innerBlocks_length });
        }, [innerBlocks_length]);

        return (
            <div className={className}>
                <div className="innerBlocks_wrapper">
                    <InnerBlocks />
                </div>
            </div>
        );
    },
    save: props => {
        const { innerBlocks_length } = props.attributes;

        return (
            <div>
                {innerBlocks_length > 0 && (
                    <div className="innerBlocks_wrapper">
                        <InnerBlocks.Content />
                    </div>
                )}
            </div>
        );
    }
});

Leave a Comment