Loading React in a WordPress Theme
Now that WordPress ships with React, it is important to know how to properly enqueue it your themes.
The overall process includes the following:
- List
wp-element
as a dependency for your own React code - Setup a build tool (I recommend WP Scripts)
- Setup a custom page template where your React code will load
- Write your React code
You can check out the final source code here if you want to jump ahead.
Make React a Dependency
When you enqueue your own JavaScript you can simply include wp-element
as a dependency and all of the functions from React and ReactDOM will be loaded on the page in a global window object named wp.element
.
Here is some example code you could add to your functions.php
file:
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_script(
'my-theme-frontend',
get_stylesheet_directory_uri() . '/build/index.js',
['wp-element'],
time(), //For production use wp_get_theme()->get('Version')
true
);
}
This is all you need to do!
If your JavaScript file is located somewhere else you will want to change /build/index.js
, however, this will work with the default settings for WP Scripts.
Setup Your Build Tool (WP Scripts)
WP Scripts is a command line toolkit from the WordPress team that will bundle your JavaScript code. It includes webpack as well as some other tools and makes them all work with very little configuration.
To start, create a package.json file
in the root folder of your theme and add the following:
{
"name": "theme-name",
"version": "1.0.0",
"description": "A demo theme with React",
"main": "index.js",
"devDependencies": {
"@wordpress/scripts": "^5.1.0"
},
"scripts": {
"build": "wp-scripts build",
"check-engines": "wp-scripts check-engines",
"check-licenses": "wp-scripts check-licenses",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"start": "wp-scripts start",
"test:e2e": "wp-scripts test-e2e",
"test:unit": "wp-scripts test-unit-js"
},
"author": "Zac Gordon",
"license": "ISC"
}
Then run npm install
. This will get everything setup and installed for you.
Now, you can create your main JavaScript/React file at /src/index.js
and WP Scripts will automatically bundle everything and save it to /build/index.js
.
You can change the entry and output paths for the webpack configuration, but it is easiest to just use the defaults.
Create a Custom Page Template
For this demo we will create a simple custom page template inside a Twenty Twenty Child Theme that you can find the full code for here.
<?php
/**
* Template Name: React Template
*/
get_header();
?>
<main id="site-content" role="main">
<article class="post-2 page type-page status-publish hentry">
<?php get_template_part( 'template-parts/entry-header' ); ?>
<div class="post-inner thin">
<div class="entry-content">
<div id="react-app"></div><!-- #react-app -->
</div><!-- .entry-content -->
</div><!-- .post-inner -->
</article><!-- .post -->
</main><!-- #site-content -->
<?php get_template_part( 'template-parts/footer-menus-widgets' ); ?>
<?php get_footer(); ?>
The important thing is that we have a custom div with an id of react-app
. This is where we will load our custom React code.
You could also have your React code added to a header, footer, widget area or pretty much anywhere on a WordPress site you need it.
Write Your React Code
Now we can create our /src/index.js
file and add some React code.
Here is some basic code to create a <Vote /> component that let’s people click a button to increase the count of votes. It is not very practical and the data does not get saved or connected to WordPress, but it does demonstrate how to write React in your WordPress Theme.
const { render, useState } = wp.element;
const Votes = () => {
const [votes, setVotes] = useState(0);
const addVote = () => {
setVotes(votes + 1);
};
return (
<div>
<h2>{votes} Votes</h2>
<p>
<button onClick={addVote}>Vote!</button>
</p>
</div>
);
};
render(<Votes />, document.getElementById(`react-app`));
The code above will display a button that increases the votes on click. You can customize this as needed as well as begin creating and importing in other files and components as you would expect with a React app.
Happy Reacting!
React will become more commonplace in WordPress themes and plugins so hopefully this article helps you get more comfortable loading and using React in your projects.