Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add JavaScript to a Wordpress Gutenberg custom block?

Using Wordpress custom blocks, I'm currently trying to create a popover component that contains a button and a hidden content. The hidden content should appear when the user clicks on or hovers over the button (on the frontend of the website, not in the block editor).

However, when I add an onClick or onHover to the button, the event handler is not executed.

Additionally, trying to use the useState hook to store the display state of the popover crashes my block editor.

This is what my save method code currently looks like:

export default function save() {

    const [shouldDisplay, setShouldDisplay] = useState(false);

    const handleClick = () => {
        console.log('Click confirmed.');
        setShouldDisplay(!shouldDisplay);
    }

    return (
        <div {...useBlockProps.save()}>
            {/* Button with onClick handler */}
            <button onClick={() => handleClick()}>Show hidden content!</button>

            {/* Hidden content */}
            { shouldDisplay && <div class="popover-content">...</div> }
        </div>
    )
}

The answer to this similar(?) question seems to suggest it is not possible as the frontend just renders "static html" and strips off the javascript. If that is the case, what would be good approach to create user interactivity (hover/click events or even possible http requests) in the frontend of Wordpress custom blocks?

like image 440
Drikus Roor Avatar asked Oct 20 '25 10:10

Drikus Roor


2 Answers

Since WordPress 5.9.0 you have to use viewScript to define the frontend JS file in the block.json:

{ "viewScript": "file:./view.js" }

See the reference: https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script

like image 93
Eingenetzt Avatar answered Oct 21 '25 23:10

Eingenetzt


In your blocks.json file you can define a js file to be executed on the front end.

{
  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 2,
  "name": "create-block/xxxxx",
  "version": "x.x.x",
  "title": "xxxx",
  "category": "xxxx",
  "description": "xxxx",
  "attributes": {
    "example":{
      "type":"string"
    },
  "supports": {
    "html:": true
  },
  "textdomain": "xxxxx",
  "editorScript": "file:./xxxx.js",
  "editorStyle": "file:./xxxx.css",
  "script": "file:./index.js", <--
  "style": "file:./xxxx-xxxx.css"
}

Reference https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script

like image 43
Michael Hegner Avatar answered Oct 21 '25 23:10

Michael Hegner