How to embed a React application into a WordPress block for rendering by the end user?
P粉790819727
P粉790819727 2023-08-17 21:15:10
0
1
387
<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粉790819727
P粉790819727

reply all(1)
P粉321584263

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 />);
     });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!