Embed Multiple React Components in WordPress
A technical guide on integrating multiple React components into a WordPress site using custom plugins and shortcodes.
WordPress is a powerful CMS, but sometimes you need the interactivity of React. Integrating multiple components into a single site can be tricky if not handled correctly.
The Approach
We can create a custom WordPress plugin that enqueues our React bundle and provides shortcodes for different components.
1. The Plugin Structure
// my-react-plugin.php
add_shortcode('react_component_one', 'render_component_one');
function render_component_one() {
return '<div id="react-root-one"></div>';
}2. Rendering in React
In your React application, use createRoot for each entry point:
import { createRoot } from "react-dom/client";
import ComponentOne from "./ComponentOne";
const rootOne = document.getElementById("react-root-one");
if (rootOne) {
createRoot(rootOne).render(<ComponentOne />);
}Why this works
By using unique IDs and conditional rendering, you can sprinkle React interactivity throughout your legacy WordPress site without a complete rewrite.
This "micro-frontend" approach on top of WordPress is a great way to modernize your tech stack incrementally.