0

So I have been trying to embed a react component into a existing wordpress project based on the roots/sage setup.

Have been searching through the internet for guides on how to do this and I can't find any way to do this.

When I read the wordpress guide it looks like it should be easy and react & react-dom should be available in wp.element. https://developer.wordpress.org/block-editor/packages/packages-element/

On the wp.element global object, you will find the following, ordered roughly by the likelihood you’ll encounter it in your code:

<div id="greeting"></div>
<script>
function Greeting( props ) {
    return wp.element.createElement( 'span', null, 
        'Hello ' + props.toWhom + '!'
    );
}
 
wp.element.render(
    wp.element.createElement( Greeting, { toWhom: 'World' } ),
    document.getElementById( 'greeting' )
);
</script>

So what I have been trying to get working is just to print a basic hello world from a react component to start with. But I haven't come further than wp.element is undefined.

I have no idea how to get this working. Does someone have experience in doing this?

1 Answers1

0

You would need to enqueue the react script, something like this

            wp_register_script(
                'react',
                get_template_directory_uri() . '/build/index.js',
                ['wp-element'],
                '0.01'
            );
            wp_enqueue_script('react');

And then in the index.js you would have access to wp.element

GWorking
  • 4,011
  • 10
  • 49
  • 90