Running a React App Through WordPress
In this tutorial, we will be exploring how to run a React app through WordPress. This tutorial assumes that you have a basic understanding of React and familiarity with PHP and the way WordPress Core works.
Why add React to WordPress?
WordPress is a free and open-source content management system written in PHP and paired with a MySQL or MariaDB database. It works great at managing content, but it is not the best at creating dynamic, interactive user interfaces. React can be used to create a dynamic, interactive user interface.
How to add React to WordPress
Step 1: Create a folder in your theme or plugin directory
In my example, I will be adding React to a plugin. You will also need to make sure you have Node.js installed on your computer.
Create a new folder in the theme or plugin you want to add React to. I will be adding React to a plugin, so I will create a folder called react-app
in my plugin’s directory.
Step 2: Create a React app in the folder
Open a terminal in the react-app
directory and create a new React app.
Then follow the wizard instructions to create a new React app. Once your React app has been created, install the @wordpress/scripts
package.
Then open the /react-app/package.json
file and add the following scripts.
In your /src/index.js
file, replace the React and ReactDOM imports with the render method from wp.element, and the root.render method with the render method from wp.element.
Then you can run npm start
to build your React app.
Step 3: Create a PHP file in the folder
Create a new PHP file in the react-app
folder. I will be calling my file index.php
. You will want to set up the file to register the react script and styles, and render the app via a shortcode. In my example, I am using “ra” as a prefix to help prevent conflicts with other plugins.
Step 4: Include the PHP file in your theme or plugin
In your theme or plugin’s main PHP file, include the PHP file you created in step 3.
Step 5: Add the shortcode to your WordPress site
Now you can add the shortcode to a page on your WordPress site. Voila! You now have a React app running through WordPress!
When you are ready to build your React app for production, you can run npm build
to build your React app.