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?
3
Answers
For now I have been able to solve the issue by enqueueing a custom script in the Wordpress plugin I have created for my custom blocks:
But if anyone finds a better solution I would be very interested to know!
index.php: (the main plugin file)
index.js (the enqueued script)
save.js (the custom block's save function)
In your blocks.json file you can define a js file to be executed on the front end.
Reference
https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script
Since WordPress 5.9.0 you have to use viewScript to define the frontend JS file in the block.json:
See the reference:
https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#script