2

So it's a pretty simple question and I've searched a lot on the internet. I found out there's a lot of people still wondering why a feature like this is not already available.

I need to use React on the frontend (typically the save.js file) of my Gutenberg block. Has anyone found a solution to this problem yet? Is the Gutenberg dev team looking into a solution or possible new features to this product?

2 Answers 2

1

I had a same question before so just wanna share my answer here just in case if anyone need it.

basically, the save function just returns a html string which will be saved to DB and rendered on front end, so don’t expect it would handle any logical function within it.

A solution for this one is you need to attach a js file on frontend, which will hydrate the react events to the dom element once it is rendered on front end side. For any attributes attached to the block, you also need to get all of them and put to the props of the react element.

This is an example that you can take a look https://github.com/trykoszko/gutenberg-block-hydration-example

0

If I understand the question correctly, the Woocommerce team came up with a really cool soultion a while back.

You can read a basic explenation here: https://developer.woo.com/2021/11/15/how-does-woocommerce-blocks-render-interactive-blocks-in-the-frontend/

The idea is you have to modify the usual WP block setup to include a frontend.js file that replaces the gutenberg block with your react file:

import Block from './block';
import {render, Suspense} from "@wordpress/element";

window.addEventListener('DOMContentLoaded', () => {
    const customBlocks = document.querySelectorAll('.block-class-selector');

    if (customBlocks.length) {
        customBlocks.forEach(customBlock => {
            const attributes = {...customBlock.dataset};

            render(
                <Suspense fallback={<div className="wp-block-placeholder"/>}>
                    <Block {...attributes} />
                </Suspense>,
                customBlock
            );
        })
    }
});

Using PHP, you need to collect all of the blocks attributes/settings and output them as data sets inside the container div, this allows you to access them inside your react code as attributes. It's probably too much to explain here, but I suggest you download the Woocommerce plugin and take a look at their code. They have some great classes that do all of the heavy lifting.

I hope that helps at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.