Reputation: 3001
I am just getting into Gutenberg and especially InnerBlocks. What I am trying to achive is a form of communication between parent- and inner blocks. I would e.g. love to display, how many inner blocks are created in the parent block
//registering Blocks
registerBlockType( 'xxx/outer-block', {
...
} );
registerBlockType( 'xxx/inner-block', {
...
parent: [ 'xxx/outer-block' ],
...
} );
From the edit function of outer-block
edit: ( { attributes, setAttributes, className, isSelected } ) => {
return (
<div className={ className }>
<p>There are { innerBlockCount } innerBlocks</p>
<p>One of the inner blocks is selected: { isInnerBlockSelected }</p>
<InnerBlocks />
</div>
);
I managed to get innerBlockCount
with the wordpress withSelect
-function like so:
export default compose( [
withSelect( ( select, ownProps ) => {
const blocks = select( 'core/editor' ).getBlocksByClientId( ownProps.clientId );
const innerBlocks = blocks.length ? blocks[ 0 ].innerBlocks : [];
return {
innerBlocks: innerBlocks,
innerBlocks: select( 'core/editor' ).getBlocks( ownProps.clientId ),
innerBlocksCount: innerBlocks.length,
};
} ),
withNotices,
] )( OuterBlock );
But I am having a hard time, to inform the outer block, when one of the innerBlocks is selected. My goal is to create something like an "edit-mode" of my block that automatically gets enabled, when the block or one of the child blocks is active.
Upvotes: 4
Views: 4723
Reputation: 657
Glad to know that you already tried and figure out something.
As you already know that Gutenberg is a React based editor and on react components there are states due to which the app handles/use the data so logically Gutenberg should also have to store this data somewhere and I am glad to tell you that it not only stores the data but also provide getters and setters. Gutenberg store this data in its Data Module the one that you already use and here is its reference page.
As I imagine you already have studied some of that and find out that it's not very developer friendly docs but there is a friendly and fast way to get access to all of the functions and testing that.
For each of data module you can see all available getters and setters in your browser console and also test them from console. There is only one condition that you must have to be in the Gutenberg Editor screen while using console.
On console write the following select methods to get getters and dispatch methods to get setters.
wp.data.select('core')
wp.data.dispatch('core')
wp.data.select('core/blocks')
wp.data.dispatch('core/blocks')
wp.data.select('core/block-editor')
wp.data.dispatch('core/block-editor')
and more I think you get the idea go to that reference page and pass that module to wp.data.select()
or wp.data.dispatch()
and then you can get or set data. I hope it will help you to solve all of your current problem and possibly the future ones also.
Upvotes: 2