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.
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.
Share Improve this question edited Aug 16, 2019 at 13:51 jshwlkr asked Aug 15, 2019 at 20:29 jshwlkrjshwlkr 5341 gold badge6 silver badges24 bronze badges 2- Can you clarify if you are talking about altering the block output of a block you are currently writing yourself, want to change the behavior of an existing block or just want to change the looks on the frontend? Also if you have code that might help. – kraftner Commented Aug 16, 2019 at 10:29
- I'm working in a custom block. I just want to alter the front end based on whether or not a user has actually entered any innerblocks. – jshwlkr Commented Aug 16, 2019 at 13:47
1 Answer
Reset to default 4I 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>
);
}
});