Headless WordPress with React
Tags: wordpress, javascript, react, wpapi
Published: 2017-02-13 19:01:38

---
title: Headless WordPress with React
published: true
description: An intro to building decoupled WordPress-powered websites using the WordPress REST API and Create ReactÂ App
cover_image: 
tags: wordpress, javascript, react, wp-api
---
![](https://cdn-images-1.medium.com/max/2000/1*XbuZMvyieZQen4Cmk6QbUA.png)

## An intro to building decoupled WordPress-powered websites using the WordPress REST API and Create ReactÂ App

In recent months, I've taken a big interest in the WordPress REST API (hereto referred to as the WP-API) and React. I've been writing an introductory series to the WP-API, but decided to break for a more full-length, detailed post.

This post will outline how to get started building decoupled (or “headless”) WordPress web applications with Create React App and the WP-API. While this post is going to focus on React for the frontend, some of the general concepts still apply if you want to build your frontend with something else such as Angular, Rx, Ember, or Vue.

And you don't have to stop with web applications. You can use the WP-API to power not only web applications, but also mobile apps, gaming console apps, and more, simultaneously.

Before getting started, feel free to [clone the repository for this demo](https://github.com/jchiatt/headless-wp).

## Why?

### Why WordPress?
Your first question may be “why should I care that WordPress has an API?” I've already written about this a bit [in another post](https://notes.builtbygood.co/getting-started-with-the-wordpress-rest-api-part-1-intro-66cf14d3ebb1#.awujhv69a), but if you aren't up for opening another tab, here are a few highlights:

1. **As of November, [WordPress now powers over 27% of the web](https://wptavern.com/wordpress-passes-27-market-share-banks-on-customizer-for-continued-success)**. And as of version 4.7, released just a couple of months ago, all the content endpoints for the WP-API are now included in WordPress core, so millions of new APIs just went online.

2. **WordPress is super user-friendly.** This may be the single biggest reason why WordPress has seen such widespread adoption. It allows anyone, even non-technical people, to create and edit a website. There is no other tool with the same amount of features and support in existence that's as empowering as WordPress.

3. **WordPress is a powerful content management platform**. It's a common misconception among some developers who have never used WordPress (or who haven't used it in a long time) that WordPress is merely for blogging. While it's great for blogging, it's actually great for effectively managing custom content via [Custom Post Types](https://codex.wordpress.org/Post_Types#Custom_Post_Types).

### Why Create ReactÂ App?
Unless you've been living under a rock in the web development world, you've undoubtedly heard of [React](https://facebook.github.io/react/) by now. Going into the background of React is beyond the scope of this article, but I do want to introduce you to [Create React App](https://github.com/facebookincubator/create-react-app), the easiest way to get started with React.

Getting started with React itself is pretty easy. You can drop React and ReactDOM into your application today:

```
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
```

But if you're looking at using React on more than one small part of your application, the depth of the rabbit hole can quickly become overwhelming. Wanting to deeply learn React usually leads to a plethora of over things to learn: ES6, JSX, Babel, Webpack, and much moreâ€Š–â€Šeach of these requiring a significant time investment to really understand.

Then, even after acquiring a deep knowledge of these subjects, you'll still spend a significant amount of time in configuration on most non-trivial projects.
But what if you just want to try React itself? Or what if you want to start with a set of configuration defaults and then modify those defaults as you go along?

Well, there's hope: Create React App.

Last summer, Facebook released Create React App, a boilerplate tool with a sensible set of configuration standards so you can quickly get started with React itself and then go down the rabbit hole at your own pace.

Create React App comes bundled with Webpack, ESLint, Babel, Autoprefixer, Jest, and other great tools from the community.

### Why Headless WordPress?
Okay, so WordPress is great. React is great. So why should we combine the two?

1. **JavaScript is the future of WordPress**. In late 2015, Automattic, the company behind WordPress, re-wrote their entire admin application ([codenamed “Calypso”](https://developer.wordpress.com/calypso/)) in JavaScript. And a few weeks later, Matt Mullenweg, CEO of Automattic, gave a massive homework assignment to all WordPress developers: “[learn JavaScript, deeply](http://wesbos.com/learn-javascript/).”

2. **Because a frontend/backend split is good for the worldâ€Š–â€Šboth users and developers**. Better user experiences are possible. Maintaining large codebases is more efficient. Better performance.

3. **Your company can hire more specialized talent**. Frontend engineers don't have to know WordPress and vice-versa. Instead of hiring a generalist WordPress theme/plugin developer, you can hire separate roles who each have a deep knowledge of frontend engineering and Wordpress, respectively.

## Onward!
Okay, so now that we've established why this matters, let's dive in!

### What We'll BeÂ Building
For this tutorial, we'll be building a simple app that displays data about each of the Star Wars movies. The data will be supplied by a WordPress REST API we'll build, and we'll consume it with a React frontend built with Create React App.

### Step One: Create New WordPress Installation

I won't go into much depth on this, as there are thousands of resources on the web for setting up a WordPress installation.

If this is your first time delving into WordPress, then I'll assume you don't have a local environment set up. There are some out-of-the-box solutions, such as MAMP and DesktopServer, which are great for getting going quickly. Currently, I'm using [Vagrant with Varying Vagrant Vagrants and Variable VVV](http://wpbeaches.com/setting-up-a-wordpress-vvv-vagrant-workflow/).

![vv + VVV = Awesome Local Environment for WordPress](https://cdn-images-1.medium.com/max/800/1*YrT0wVD89S07t0R-8vLQug.png)

Once you have your new WordPress install set up, go ahead and visit your admin dashboard: `http://your-site.dev/wp-admin`

![Look at that fancy new install! âœ¨](https://cdn-images-1.medium.com/max/800/1*0aC-EcmtvoinClX9nU6eSg.png)

### Step Two: Install the WordPress REST API Plugin (may not be required)
This step is only required if you are running a WordPress version older than 4.7. You can check what version of WordPress you are running by going to Dashboard>Updates:

~![WordPress Dashboard - Updates Section](https://cdn-images-1.medium.com/max/800/1*aFi-cQnBZaveO_iTzCuLpA.png)

As of WordPress 4.7, the WP-API is [integrated into WordPress core](https://developer.wordpress.org/rest-api/). So if you're running 4.7 or greater, you're good to go.

Otherwise, navigate to Plugins>Add New and search for “WordPress REST API (Version 2)”. Go ahead and Install it and then Activate it.

### Step Three: SanityÂ Check
Fire up your favorite API request tool (I like to use Postman) or a Terminal window if you prefer.

Fire off a GET request to `http://your-site.dev/wp-json/`. You should get back some JSON that contains all your WordPress site's resources and their respective endpoints.

For a quick demo, send a GET request to `http://your-site.dev/wp-json/wp/v2/posts/1`â€Š–â€Šyou should get back JSON with information about the “Hello World!” test post that comes with all new WordPress installs by default. If you already deleted the test post, you won't get anything back.

### Step Four: Install Plugins for thisÂ Project
The next thing to do is install the plugins we'll need for this demo project. Go ahead and install these and then come back for the explanation of each (unless otherwise noted, each can be searched and installed from Plugins>Add New).

### [CPT UI](https://wordpress.org/plugins/custom-post-type-ui/)
Custom Post Types (CPTs) is one of the most powerful features of WordPress. It allow you to create custom content types to go beyond the default Posts and Pages that WordPress ships with.

While it's certainly possible (and pretty trivial) to create CPTs via PHP, I really like how easy CPT UI is to use. Plus, if you're reading this with no prior WordPress experience, I'd rather you be able to focus on the WP-API itself instead of WordPress and PHP.

For our demo, we'll be creating a CPT called Movies.

I'm going to cover how to manually add the Movies CPT, but if you'd like to skip that and just import the data, go to CPT UI>Tools and paste in the following:

```
{
"movies": {
"name": "movies",
"label": "Movies",
"singular_label": "Movie",
"description": "",
"public": "true",
"publicly_queryable": "true",
"show_ui": "true",
"show_in_nav_menus": "true",
"show_in_rest": "true",
"rest_base": "movies",
"has_archive": "false",
"has_archive_string": "",
"exclude_from_search": "false",
"capability_type": "post",
"hierarchical": "false",
"rewrite": "true",
"rewrite_slug": "",
"rewrite_withfront": "true",
"query_var": "true",
"query_var_slug": "",
"menu_position": "",
"show_in_menu": "true",
"show_in_menu_string": "",
"menu_icon": "",
"supports": [
"title",
"editor",
"thumbnail"
],
"taxonomies": [],
"labels": {
"menu_name": "",
"all_items": "",
"add_new": "",
"add_new_item": "",
"edit_item": "",
"new_item": "",
"view_item": "",
"search_items": "",
"not_found": "",
"not_found_in_trash": "",
"parent_item_colon": "",
"featured_image": "",
"set_featured_image": "",
"remove_featured_image": "",
"use_featured_image": "",
"archives": "",
"insert_into_item": "",
"uploaded_to_this_item": "",
"filter_items_list": "",
"items_list_navigation": "",
"items_list": ""
},
"custom_supports": ""
}
}
```

Now for the manual process:
1. Go to CPT UI>Add/Edit Post Types

2. For the Post Type Slug, enter `movies`â€Š–â€Šthis is the URL slug WordPress will use.

3. For the Plural Label, enter `Movies`

4. For the Singular Label, enter `Movie`

5. **IMPORTANT:** Scroll down to the Settings area and find the “Show in REST API” option. By default, this is set to False. If you don't change it to True, you will not be able to query this CPT using the WP-API. Right underneath that option, you should see the “REST API base slug” optionâ€Š–â€Šyou can enter `movies` here.

6. Scroll all the way down and click Add Post Type.

You should see a new Movies option appear in the sidebar:

![Movies appeared in the WordPress Dashboard side bar](https://cdn-images-1.medium.com/max/800/1*nC3WA7xPEN6VTGiuRf-SZw.png)

#### [Advanced Custom Fields](https://wordpress.org/plugins/advanced-custom-fields/)
Speaking in database terms, if CPTs are the tables, Custom Fields are the columns. This isn't actually how WordPress stores CPTs and Custom Fields in its database, but I find this illustration helpful to those who have limited to no WordPress experience. CPTs are the resource (i.e. “Movies”) and Custom Fields are the metadata about that resource (i.e. “Release Year, Rating, Description”).

Advanced Custom Fields (ACF) is the plugin for WordPress Custom Fields. Of course, you can create Custom Fields with PHP (just like CPTs), but ACF is such a time-saver (and it's a delight to use).

You can get this one from Plugins>Add New, but if you want to use the import function to import my sample data, you'll need the Pro version, [which you can find here](https://www.advancedcustomfields.com/pro/)).

If you have the Pro version, go to Custom Fields>Tools after Activating the plugin. You can then paste in this JSON to import the fields you'll need:

```
[
{
"key": "group_582cf1d1ea6ee",
"title": "Movie Data",
"fields": [
{
"key": "field_582cf1d9956d7",
"label": "Release Year",
"name": "release_year",
"type": "number",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"default_value": "",
"placeholder": "",
"prepend": "",
"append": "",
"min": "",
"max": "",
"step": ""
},
{
"key": "field_582cf1fc956d8",
"label": "Rating",
"name": "rating",
"type": "number",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"default_value": "",
"placeholder": "",
"prepend": "",
"append": "",
"min": "",
"max": "",
"step": ""
},
{
"key": "field_5834d24ad82ad",
"label": "Description",
"name": "description",
"type": "textarea",
"instructions": "",
"required": 0,
"conditional_logic": 0,
"wrapper": {
"width": "",
"class": "",
"id": ""
},
"default_value": "",
"placeholder": "",
"maxlength": "",
"rows": "",
"new_lines": "wpautop"
}
],
"location": [
[
{
"param": "post_type",
"operator": "==",
"value": "movies"
}
]
],
"menu_order": 0,
"position": "normal",
"style": "default",
"label_placement": "top",
"instruction_placement": "label",
"hide_on_screen": "",
"active": 1,
"description": ""
}
]
```

If you don't have the Pro version, here's how to setup your Custom Fields:

##### Create the Field Group
ACF organizes collections of Custom Fields in Field Groups. This is domain-specific to ACF. That's all you really need to know about Field Groups for now.

1.Go to Custom Fields>Field Groups

2. Click “Add New”

3. For the Field Group title, enter “Movie Data”

4. Scroll down until you see the Location metabox. Set this Field Group to only show if Post Type is equal to Movie:

![ACF Display Settings for Field Group](https://cdn-images-1.medium.com/max/800/1*3m-RDPKxZ8Ob8zeJ9DT1iw.png)

You can then scroll down to the Settings metabox. You should be able to leave all these options set to their defaults, but you can still give it a once over compared against this screenshot:

![ACF Movies field group settings](https://cdn-images-1.medium.com/max/800/1*bT2V5DJ6L4wMrUbYmpFtNg.png)

After that, click Update to save your Field Group settings.

##### Create the Custom Fields
First, create a Release Year field:

```
Field Label: Release Year
Field Name: release_year
Field Type: Number
Required? No
```

Next is the Rating field:

```
Field Label: Rating
Field Name: rating
Field Type: Number
Required? No
```

And lastly, the Description field:

```
Field Label: Description
Field Name: description
Field Type: Text Area
Required? No
```

Don't forget to click Update to save your new Custom Fields.

Now, if you to to Movies>Add New, and then scroll down a bit, you should see a metabox called Movie Data (the name of your field group) along with each of the Custom Fields you created inside it:

![The Movies field group now appears if on the New Movie page](https://cdn-images-1.medium.com/max/800/1*c4XMim3_po5NMXwO3TQVUg.png)

#### [ACF to REST API](https://wordpress.org/plugins/acf-to-rest-api/)
Now that we have our Custom Fields, we need to expose them to the WP-API. ACF doesn't currently ship with WP-API support, but there's a great plugin solution from the community called ACF to REST API. All you have to do is install (you can find it by searching for it at Plugins>Add New) and activate it, and it will immediately expose your ACF custom fields to the API.

If we had created our Custom Fields directly via PHP (without the use of a plugin), there's also a couple of nifty functions for exposing the field to the API. [More on that here](https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/).

### Step Five: Post DataÂ Import
This is the last step to get our WordPress installation ready to serve our Star Wars data.

First, we need to import all the Movies. Lucky for you, I already did all the manual work and all you have to do is import a nifty file.Â :-)

Go to Tools>Import. At the bottom of the page you should see an option to import from WordPress with an Install Now link underneath:

![Screenshot of WordPress Import screen](https://cdn-images-1.medium.com/max/800/1*Eqc1XFQ9G9wjcop-FcCM5w.png)

After the WordPress Import installs, you should see a link to run the importer. Click that and [import this file at the next screen](https://gist.github.com/jchiatt/75b9d8218c09a8a881770399343da69a#file-movie-data-xml).

The next screen will ask you to assign the imported posts to an author. You can just assign them to your default admin account and click Submit:

![Post-import screen for new author assignment](https://cdn-images-1.medium.com/max/800/1*gWmhR0zB7-SOVWcQErYjpQ.png)

Lastly, go to Movies>All Movies. You should see a listing of Star Wars movies (Episodes 1–7). Because I developed in my local environment, the import file couldn't import the featured images for the Movies (it couldn't fetch them from the origin server), so you'll have to add those manually (it only takes about 30 seconds).

My preferred way (and the fastest way) is to hover over each of the posts on the All Movies page and hold Command (Control on Windows) and click Edit for each one. This will open one tab for each Movie.

On each of the edit pages, in the right sidebar, find the Featured Image metabox and click Set Featured Image. [Here's a ZIP file with each of the images you'll need](http://files.builtbygood.co/B8Ej/1YcE71CU). Or you can use any other images you'd like.

For the first one, it's easiest to upload all the images to the Image modal that you see when you click Set Featured Image and then only select the one you need for that first Movie (this will save you the time of uploading each image individually across all your Movies):

If that seems unclear, [here's a GIF](http://files.builtbygood.co/2z0c/5gaJ5HKh) that will hopefully make more sense than my poor attempt at explanation.

For each Movie, be sure to click Update after selecting featured image.

Now you're good to go! Now leave your WordPress server running and let's move on.

### Step Six: Install Create ReactÂ App
Assuming you already have Node and npm installed on your machine, simply run this command:
```
npm install -g create-react-app
```
That's it! You're ready to use Create React App.

### Step Seven: Create theÂ App
`cd` into the directory you'd like to create the frontend (this doesn't have to be (and shouldn't be) the same directory as your WordPress installation). Then run:

```
create-react-app headless-wp
```

The process will take a few minutes, but once it's complete you should be able to cd into the newly created `headless-wp` directory. From there, run:

```
npm start
```

This command fires off a number of things, but all you need to know at the moment is that it'll boot up a Webpack dev server. Your browser should automatically open to `http://localhost:3000`:

![The default page when you first boot up your new React app.](https://cdn-images-1.medium.com/max/800/1*runBBJVfSbKfNcl1fsi-Fg.png)

You can leave the server running in your shell. Hot reloading will automatically refresh your webpage every time you save a file.

### Step Eight: Create Your Component
Since this demo app is very simple, we'll only be using one component. We could easily create another component (it's as easy as creating another `ComponentName.js` file and importing it into its parent component), but we're instead going to edit our `App.js` component.

Open up `App.js`. You can go ahead and delete all the existing code from this file except for the first and last lines.

At this point, `App.js` should look like this:

```
import React, { Component } from 'react';
export default App;
```

Next, create the `render()` function for this component. This function gets called every time the state changes. If you aren't sure what this means, have some patience. It'll make sense soon.

`App.js` should now look like this:

```
import React, { Component } from 'react';
class App extends Component {
  render() {
    return (
      <div>
        <h2>Star Wars Movies</h2>
      </div>
    )
  }
}
export default App;
```

Whatever `render()` returns is what gets painted on the DOM. If you save this file and go back to your browser, it should automatically reload and you should see this `h2` we created:

![A shiny new h2!](https://cdn-images-1.medium.com/max/800/1*FxZzfD4dJynhMAx7ESVWkg.png)

This is great and all, but what about all that great data we stored in WordPress about the Star Wars movies? Time to get that data!

Update `App.js` like so:

```
import React, { Component } from 'react';
class App extends Component {
  constructor() {
    super();
    this.state = {
      movies: []
    }
  }
componentDidMount() {
    let dataURL = "http://headless-wp.dev/wp-json/wp/v2/movies?_embed";
    fetch(dataURL)
      .then(res => res.json())
      .then(res => {
        this.setState({
          movies: res
        })
      })
  }
render() {
return (
      <div>
        <h2>Star Wars Movies</h2>
      </div>
    )
  }
}
export default App;
```

We just added two new functions to our `render()` function: `constructor()` and `componentDidMount()`.

The `constructor()` function is where we initialize state. Since we're only dealing with some JSON about our movies, our state is going to be pretty simple. Our initial state will just be an empty `movies` array since we're expecting to get back that JSON.

The `componentDidMount()` function fires after the component mounts. This is the best place to make external API calls, so this is where we've added our code to use the [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to grab all the movies from our WordPress API (be sure to update the URL to reflect your own URL!). Then, we're taking the response, parsing it as JSON, and then pushing it into our state object.

Once the response gets pushed into our state, the component will re-render by firing the `render()` function because the state has changed. But this doesn't really matter right now, because currently our `render()` function is still only returning a div with a `h2` inside.

Let's fix that.

We're now going to add a bit of extra code to our `render()` function that will take the JSON in the our state (currently stored in `this.state.movies`) and `map` each movie and its data into a `div`.

`App.js` should now look like this:

```
import React, { Component } from 'react';
class App extends Component {
  constructor() {
    super();
    this.state = {
      movies: []
    }
  }
componentDidMount() {
    let dataURL = "http://headless-wp.dev/wp-json/wp/v2/movies?_embed";
    fetch(dataURL)
      .then(res => res.json())
      .then(res => {
        this.setState({
          movies: res
        })
      })
  }
render() {
    let movies = this.state.movies.map((movie, index) => {
      return <div key={index}>
      <img src={movie._embedded['wp:featuredmedia'][0].media_details.sizes.large.source_url} />
      <p><strong>Title:</strong> {movie.title.rendered}</p>
      <p><strong>Release Year:</strong> {movie.acf.release_year}</p>
      <p><strong>Rating:</strong> {movie.acf.rating}</p>
      <div><strong>Description:</strong><div dangerouslySetInnerHTML={ {__html: movie.acf.description} } /></div>
      </div>
    });
return (
      <div>
        <h2>Star Wars Movies</h2>
      </div>
    )
  }
}
export default App;
```

If you save your file, the page will reload, but you still won't see the Star Wars movie data load on the page. That's because there's one last thing to add. We're mapping each of our movies to their own respective divs, and then storing all those movies inside the `movies` variable in our `render()` function. Now we just need to tell our `render()` function to return our `movies` variable by adding `{movies}` underneath our `h2`.

Finished `App.js`:

```
import React, { Component } from 'react';
class App extends Component {
  constructor() {
    super();
    this.state = {
      movies: []
    }
  }
componentDidMount() {
    let dataURL = "http://headless-wp.dev/wp-json/wp/v2/movies?_embed";
    fetch(dataURL)
      .then(res => res.json())
      .then(res => {
        this.setState({
          movies: res
        })
      })
  }
render() {
    let movies = this.state.movies.map((movie, index) => {
      return <div key={index}>
      <img src={movie._embedded['wp:featuredmedia'][0].media_details.sizes.large.source_url} />
      <p><strong>Title:</strong> {movie.title.rendered}</p>
      <p><strong>Release Year:</strong> {movie.acf.release_year}</p>
      <p><strong>Rating:</strong> {movie.acf.rating}</p>
      <div><strong>Description:</strong><div dangerouslySetInnerHTML={ {__html: movie.acf.description} } /></div>
      </div>
    });
return (
      <div>
        <h2>Star Wars Movies</h2>
        {movies}
      </div>
    )
  }
}
export default App;
```

Switch back over to your browser window and you should see the Star Wars data after the page reloads:

![May the Force be withÂ you.](https://cdn-images-1.medium.com/max/800/1*XbuZMvyieZQen4Cmk6QbUA.png)

## Going Further
This is only the beginning of what you can do with the WP-API and React. Both have many other features and both have **huge** communities.

You can take the WP-API further by learning about authentication and POST requests, custom endpoints, and more complex queries.


And as I said earlier, Create React App is made for you to just get your feet wet. When you're ready to learn more, you can learn more about things like Redux, ES6, Webpack, React Native, and more.

I'll be covering many of these topics and more in future posts, so be sure to check back. Or if you'd prefer to have these posts sent directly to your inbox, [shoot me an email](mailto:jc@builtbygood.co) and I'll add you to my mailing list.

## Questions?
I'm happy to help! Leaving a comment below is the fastest way to get a response (plus, it helps others who have the same problem!). Otherwise, [drop me a line on Twitter](https://twitter.com/jchiatt) or [shoot me an email](mailto:jc@builtbygood.co) and I'll do what I can to help!