How to Add Onclick Event Inside Gutenberg Block – WordPress

have been searching everywhere to figure out how to add an event inside a Gutenberg block. I am working to add an accordion system using ACF and Foundation. I have created a block and fields and template using ACF. I would like my users to be able to open and close the accordion in the visual mode.

I did find the following script that monitors when blocks are changed. The only issue is that it fires before everything is loaded and I had to use a timeout to allow the blocks to fully load. I have been unable to find a better way of accomplishing this. Any suggestions?

[php]const getBlockList = () => wp.data.select( ‘core/editor’ ).getBlocks();
let blockList = getBlockList();
wp.data.subscribe(() => {
const newBlockList = getBlockList();
const blockListChanged = newBlockList !== blockList;
blockList = newBlockList;
if ( blockListChanged ) {
setTimeout(function(){
jQuery(document).foundation();
Foundation.reInit($(‘[data-accordion]’));
}, 4000);
}
});[/php]

Best Answer

On the front end you get static html just like before. If you add on click event to your component in save function, it will be stripped off during serialization so no need to sweat there. Everything works as before blocks.

However, on the editor side, you can add an event on any element in edit function’s return element:

Here is how you do it in es6:

[php]const handleClick = (event) => {
console.log(event)
}

const element = <div onClick={handleClick}>Click Me</div>;[/php]

or in es2015:

[php]var handleClick = function handleClick(event) {
console.log(event);
};

var element = React.createElement(
"div",
{ onClick: handleClick },
"Click Me"
);[/php]

By the way, this is a gutenber block, not its in memory representation rendered by react.

[php]<!– wp:paragraph {"key": "value"} –>
<p>Welcome to the world of blocks.</p>
<!– /wp:paragraph –>[/php]

[custom-related-posts title=”You may Also Like:” none_text=”None found” order_by=”title” order=”ASC”]

Leave a Comment