So I'm answering the following: How to open the block picker menu via a custom button. I.e. Without using InnerBlocks.ButtonBlockAppender
. :)
How can I open the Block Picker Menu on click of the custom button?
There's no (as of writing) "standard" function (like alert()
) that you can simply call which then opens the block picker menu; however, you can wrap your button in a Inserter
component (wp.blockEditor.Inserter
) and call it's onToggle
method/function on clicking your button.
Here's a simplified example based on ButtonBlockAppender
(the base component that's used by InnerBlocks.ButtonBlockAppender
) for the Gutenberg plugin version 8.2.1.
// WordPress dependencies.
import { Inserter, InnerBlocks } from '@wordpress/block-editor';
import { IconButton } from '@wordpress/components';
import { registerBlockType } from '@wordpress/blocks';
function MyButtonBlockAppender( { rootClientId } ) {
return (
<Inserter
rootClientId={ rootClientId }
renderToggle={ ( { onToggle, disabled } ) => (
<IconButton
className="my-button-block-appender"
onClick={ onToggle }
disabled={ disabled }
label="Add a Block"
icon="plus"
/>
) }
isAppender
/>
);
}
registerBlockType( 'my-plugin/my-block', {
title: 'My Block',
category: 'common',
edit( { className, clientId } ) {
return (
<div className={ className }>
Click the button to add your 1st image/paragraph.
<InnerBlocks
allowedBlocks={ [ 'core/image', 'core/paragraph' ] }
renderAppender={ () => (
<MyButtonBlockAppender rootClientId={ clientId } />
) }
/>
</div>
);
},
save() {
return (
<div>
<InnerBlocks.Content />
</div>
);
},
} );
So as I said, that's a simplified example. You can just copy the original ButtonBlockAppender
component and modify it to tailor your requirements.
Happy coding!
onClick={ ( event ) => console.log( event ) }
- just call the appropriate function or whatever is needed on click.