This seems like a simple issue, but I can’t seem to find an answer. I’m using InnerBlocks to stack some paragraphs in a wrapper. If there are no blocks set I’d like to not output the wrapper at all. Is there (currently) a straight-forward way of doing this? It seems I can maybe test against InnerBlocks itself, but I haven’t seen any documentation that suggests this is reliable.
save( { attributes } ) {
return (
<div className="header__text">
<InnerBlocks.Content />
</div>
);
}
Basically I don’t need the header__text if InnerBlocks is 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>
);
}
});