Search [Enter] to search. Click anywhere to close.

September 30th, 2021

Building A WordPress Theme With React

WordPress is a fantastic platform. It’s user-friendly and extremely powerful — it’s also particularly accessible to those just starting out with web development.

For those of us just starting out with with WordPress theme development in particular, however, it’s worth noting that there are numerous ways to go about developing your very own theme.

You may have been asking yourself “can I build a WordPress theme with React?”

The answer is yes! Let’s find out how (and why) you’d want to do this.

The classic (PHP) approach

Firstly, let’s recap how a standard WordPress theme would be constructed ordinarily.

As a brief summary, the classic approach to building out your own theme is to use template files.

Simply put, these template files consist of HTML, PHP and WordPress’s own template tags (these are basically built-in WordPress functions).

Your theme will be constructed from an assortment of template files as well as other assets like stylesheets, potentially some images, and so on. You can throw some JavaScript in there too.

Let’s refer to this method as “the PHP approach“.

The JavaScript approach

React is all the rage these days, and for good reason. It can be argued that creating a WordPress theme with React is a more “modern” take over the typical PHP approach outlined above.

Nowadays, thanks to the WordPress REST API (more on this later) — the PHP approach is no longer the only viable option. Your theme can be constructed from JavaScript, almost entirely!

It’s worth noting that we’ll be using React specifically in this article, but the same principles apply to any JavaScript framework in reality.

By creating your theme in this way, you can leverage some of the many benefits of the JavaScript ecosystem:

  • build tools and bundlers such as webpack
  • testing frameworks like mocha
  • a massive assortment of other modules and packages to use via the npm repository
  • and so on…
the javascript ecosystem
The JavaScript ecosystem is massive!

To briefly summarise this, by utilizing React (or any other JavaScript solution) to create your theme you’re inheriting a lot of power!

How do I build a WordPress theme with React?

To envisage how a WordPress theme built with React may look, it’s best to break the project down in to two distinct elements. Conceptually, you’ll need to consider these two aspects:

  • the JavaScript frontend, typically a single-page app
  • the data our app will consume, accessed via the WordPress REST API

So the theme is essentially a SPA (single-page app) that communicates directly with WordPress via WordPress’s own API. That’s it, that’s all we’ll need to get started. A React application that consumes the WordPress API — that’s our theme in a nutshell.

There are many benefits to segregating your frontend and backend in this way, and we’ll go into in more depth on this specific topic a bit later. For now, let’s cover the role of the REST API in our theme.

What’s the WordPress REST API?

Think of the WordPress REST API as a set of endpoints that you can interact with by making requests from your JavaScript theme’s frontend.

During theme creation, you’ll typically use the REST API to perform tasks such as:

  • fetching posts
  • fetching pages
  • making search queries

Not only that, you can also use the REST API to write (as opposed to read) with:

  • when creating posts
  • when deleting posts
  • when editing posts

… and so on.

So in short, the WordPress API acts as a bridge between your frontend (the JavaScript app built with React, Vue or something similar) and your backend. It’s what allows you to actually access the WordPress content and functionalities within your application.

Where a theme utilizing the classic PHP approach would use template tags and other WordPress-specific functions to retrieve the necessary content or data it requires; the JavaScript equivalent leverages the REST API instead.

Let’s take a practical look at how this works.

A basic component example: PHP templates compared to the React equivalent

Hopefully it’s clear to you now, conceptually, how WordPress theme creation works with React.

Here’s a basic example to briefly portray the differences between a React theme when contrasted with the PHP-based equivalent. As stated prior, in our examples we’ll use React — but any JavaScript framework would also work in the same way.

Let’s look at displaying a single post in our example:

Fetching a single post with the PHP approach

A WordPress PHP template file to fetch a single post may look something like this:

if (have_posts()) :
    while (have_posts()) : the_post(); ?>
        <h1><?php the_title(); ?></h1>
        <div class="content"><?php the_content(); ?></div>
    <?php endwhile;
else :
    _e('Sorry, no posts matched your criteria.');

If you’ve done any kind of WordPress theme development at all, this will likely look very familiar.

If not, don’t worry — this kind of approach is the classic/typical way we’d fetch a single post within a WordPress theme. We’re using inbuilt WordPress functionality (have_posts(), the_title() and so on) and interspersing that stuff amongst our HTML output as required.

Fairly simple, huh?

Let’s contrast that with our JavaScript (React) variant.

Fetching a single post with the React approach

In our React WordPress theme, it’s significantly different.

We aren’t utilizing PHP template files as above, and as such, we don’t have access to any of that WordPress-specific template functionality as expected. Whereas the PHP approach utilizes server-side rendered templates, we’ll need a separate request to fetch our data when using the React approach:

// A component responsible for fetching a specific 
// post (by ID) from the relevant API
// We'd substitute the URL/endpoint here for the
// relevant WordPress REST API one - and we'd ensure 
// we're accessing the correct properties on the fetched post object!
const SinglePost = () => {
    const [post, setPost] = useState()
    useState(() => {
            .then(response => response.json())
            .then(post => setPost(post))
    }, [])

    return (
        {post ? (
                <div className="content">{post.content}</div>
        ) : (
            <h3>Sorry, no posts matched your criteria.</h3>

This time, once the user accesses the given endpoint – we perform a request to retrieve whatever data is required via the REST API.

We then store this data in state and output it for the user to see.

Of course, the example is semi-pseudo code to help you understand the basic premise. However, it’s worth noting that in reality you’d want quite a few additions to your single post component, including (but not limited to):

A loading spinner

We don’t have the post data on initial load, but we do make a request for it right away. There’ll still be a period where we are “fetching” the post, so we’d want to relay that to the user via a nice loading spinner.

This is a great opportunity for you to build out a nice, clean, reusable loading spinner component! Check out my article here for tips on handling this kind of thing in general within your React applications: React Tips For Beginners – How To Structure Components.

These type of operations and functionalities should be easily reusable to avoid repetition within your code. There are several important patterns you can follow to help achieve that.

Error handling

Similarly, as we’re making a separate request to retrieve our post – we need to handle what happens if this request fails in some way.

So it’s maybe not necessarily the case that our only states are “post found” or “post not found” on this page. We’d need to be mindful of that with our API interactions. It’d likely be better to show some sort of relevant error message and the option to reload in this scenario, rather than just saying “the post wasn’t found!

There are many more enhancements you can make to really help smooth out the user experience, these will likely become apparent during the creation of your own theme.

Then how do I set up a React application in my WordPress theme?

As a general (very brief) conceptual overview, attaching React to be used in your WordPress theme would work like so:

  • List wp-element as a dependency of your React code
  • Set up WP Scripts and create a package.json file at the root of your theme as per the WP Scripts documentation
  • Create a div inside index.php in which your React application will be rendered

You’ll likely be using React Router (or equivalent) to handle the navigation within your theme. This stuff would live at the “root” of your project, all other pages and components would live nested within the router.

Once you have this structure set up and working, you’re all set to start enhancing your theme in to whatever form you’d like it to be!

For more information and specifics on the process and steps outlined above, I’d particularly recommend this article: Loading React in a WordPress Theme.

But why would I want to create a WordPress theme with React (or JavaScript) in the first place?

Hopefully some of the benefits of creating your very own React or JavaScript-based WordPress theme have become apparent now. I’ll outline two of what I consider to be the main ones below:

1. We’re using JavaScript!

First and foremost, the fact that we are using React here is a massive benefit. It means we can more easily create seamless, smooth experiences for our users.

Not only that — we can easily substitute React with any other JavaScript framework. As you can see, we aren’t specifically tied to React in any way (or even JavaScript). As long as we can interact with the WordPress REST API – we can build an immersive experience for our viewership to enjoy with any almost any tooling of our choice!

We can also leverage the massive power that comes along with using the JavaScript ecosystem in general.

2. The frontend and backend are loosely coupled (or decoupled)

The frontend isn’t concerned with the backend tech at all. This makes it more portable and more loosely-coupled in that sense.

You’ll notice there is nothing WordPress-specific at all in our React theme (aside from the REST endpoints we need to communicate with!). We only care about the interactions with the REST API. This API can technically be easily substituted with any other API (or even a mock API) without us needing to adjust our theme at all.

There can be many benefits to decoupling the elements in your application where possible

This is generally seen as a good way to work.

The loose-coupling of elements in general means you aren’t as bound to a specific methodology or implementation and you can more easily swap out individual components as and when required later on.

3. The skills you learn via implementing this approach can be readily applied elsewhere

Firstly, it’s worth stating that there is absolutely nothing wrong with PHP. In some ways it’s a “comfortable” language, and a good fit for WordPress.

However, JavaScript single-page applications are simply a staple of modern web development. The JavaScript ecosystem in general is a staple of modern web development.

As such, familiarity with this way of working has many benefits.

Moving forwards, it’s a fair assumption that any (or most) frontend applications you build will be JavaScript-based, at least to a degree. Not only that, JavaScript is rife on the backend (via node).

In terms of React specifically, you’ll also have a great foundation with regards to mobile app development — React Native is a fantastic tool to build our iOS and Android applications!

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog