How to output child block attributes on a parent block
I have a custom Gutenberg block that contains a list of InnerBlocks (all the same known block), and I am trying to output the title attribute from each of those blocks in a list on the parent block.
I'm trying to get values from the innerblocks and add them to an array attribute on the parent block,
This is a simplified version of the parent block edit.js
const Edit = ( props ) = {
const { attributes: { childValuesArray }, setAttributes } = props;
const blockProps = useBlockProps();
const ALLOWED_BLOCKS = [ 'custom/child-block' ];
const { clientId } = props;
const { select } = wp.data;
const parentBlock = select( 'core/block-editor' ).getBlocksByClientId( clientId )[ 0 ];
const childBlocks = parentBlock.innerBlocks;
childBlocks.map(block = {
childValuesArray.push( block.attributes.title, block.clientId );
});
props.setAttributes({ 'childValuesArray': childValuesArray });
return (
div { ...blockProps }
div className=block-content
InnerBlocks allowedBlocks={ ALLOWED_BLOCKS } /
/div
aside
{
childValuesArray.map( (block, index) = {
return (
p id={ block.clientId }
{ block.title }
/p
)
})
}
/aside
/div
);
};
export default Edit;
The issue I'm having is that the code to grab the child block values runs continuously, so the array of values keeps getting bigger.
Research suggests that I should maybe be using withDispatch to avoid the code running every time, but the documentation is rather brief, and I haven't been able to work out how to do this correctly.
Is withDispatch the right approach here? If so, how do I go about using it? If not, what's a better approach?
Topic block-editor Wordpress
Category Web