Home  >  Q&A  >  body text

How to embed a React application into a WordPress block for rendering by the end user?

<p>I want to embed my React application in a WordPress block and serve this application to the end user. My expectation is that I can put my app in view.js, but I can't get the content of view.js to render out. I can run React fine in the block editor via Edit() in edit.js, but this is because registerBlockType uses {edit: Edit} in the block configuration object. But there is no corresponding {render: Render} option. The closest I can get to embedding my application is to output it to HTML in render.php. The render.php file renders fine (as expected for a dynamic application with an empty save callback), but this is not enough; I need to use React. </p> <p>Reference: https://developer.wordpress.org/block-editor/getting-started/create-block/block-anatomy/</p>
P粉790819727P粉790819727400 days ago391

reply all(1)I'll reply

  • P粉321584263

    P粉3215842632023-08-18 10:40:57

    One way is to use createRoot in the wordpress element function, https://developer.wordpress.org/block-editor/reference-guides/packages/packages-element/. This way we can display React components in DOM nodes. step:

    1. Define DOM nodes in render.php:

      <div id="replacement_id">要替换的内容</div>
    2. Render the application on this node by adding the following to view.js:

      window.addEventListener("load", (event) => {
           const domElement = document.getElementById("replacement_id");
           const root = createRoot(domElement);
           root.render(<App />);
       });

    reply
    0
  • Cancelreply