Wordpress Add onclick event inside Gutenberg block
Asked Answered
C

1

7

I 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?

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);
    }
});
Cracking answered 30/10, 2018 at 20:49 Comment(1)
This doesn't answer your question but for consideration, you can create accordion blocks easily with the block api, without using AFC. React has onclick functions built in. The block api can replace ACF entirely for a better uxBelleslettres
G
3

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:

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

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

or in es2015:

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

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

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

<!-- wp:paragraph {"key": "value"} -->
<p>Welcome to the world of blocks.</p>
<!-- /wp:paragraph -->
Gyrostabilizer answered 29/1, 2019 at 0:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.