How to embed a React application into a WordPress block for rendering by the end user?
P粉790819727
2023-08-17 21:15:10
<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>
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:
Define DOM nodes in render.php:
Render the application on this node by adding the following to view.js: