React requires a separate project structure. Set it up using:
npx create-react-app your-theme-react cd your-theme-react npm start
This initializes a React project with a development server.
To serve your React app in WordPress, follow these steps:
npm run build
This generates static assets in the build folder.
function theme_enqueue_scripts() { wp_enqueue_script('react-app', get_template_directory_uri() . '/build/static/js/main.js', array(), null, true); wp_enqueue_style('react-style', get_template_directory_uri() . '/build/static/css/main.css', array(), null); } add_action('wp_enqueue_scripts', 'theme_enqueue_scripts');
React communicates with WordPress through the REST API. Fetch posts dynamically:
fetch("https://yourwebsite.com/wp-json/wp/v2/posts") .then(response => response.json()) .then(data => console.log(data));
Example of a simple React component for displaying WordPress blog posts:
import { useEffect, useState } from "react"; function BlogPosts() { const [posts, setPosts] = useState([]); useEffect(() => { fetch("https://yourwebsite.com/wp-json/wp/v2/posts") .then((res) => res.json()) .then((data) => setPosts(data)); }, []); return ( <div> {posts.map((post) => ( <div key={post.id}> <h2 dangerouslySetInnerHTML={{ __html: post.title.rendered }} /> <p dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} /> </div> ))} </div> ); } export default BlogPosts;
Here’s an organized directory structure for a React-based WordPress theme:
your-theme/ │── build/ # React build output │── template-parts/ # PHP files for templates │── index.php # WordPress main template │── style.css # Theme stylesheet │── functions.php # Enqueue scripts & styles │── header.php # Theme header │── footer.php # Theme footer
To maximize performance:
Integrating React JS with WordPress can transform a static theme into a dynamic, fast, and interactive experience. By following this step-by-step guide, you can build a modern, stunning WordPress theme tailored to today’s web standards.
For more tutorials on WordPress and React development, check out Ajay Khandal’s blog and explore insightful articles like: