Is it possible to have a React Front End for your WordPress Site?
As of WordPress 4.7, developers are able to use what is called the WP REST API out of the box without the need for any additional plugins. The REST API takes all of your WordPress posts, pages, media, and anything else that can be edited in the CMS and outputs it into a JSON object that can be connected to outside of your WordPress site. What this means is you can completely decouple your WordPress front end and back end to create web pages that can interact with WP in a whole new way.
If you have been around the front end development scene for more than a minute, you have heard of the React JavaScript library. React is a library that was created by Facebook to make it easy to create user interfaces without creating what some would call jQuery soup. Having a structure to your app that isn't just random jQuery snippets allows for an easier time implementing new features, as well as an easier time onboarding new developers. Combining React with the WP REST API allows us to use WordPress as a content management system that hydrates our React app.
Let's get started
To create a React app using WordPress as the backend, we need to create two separate sites that will not interact with each other directly. So the first step is to create a WordPress site as you normally would. Once your WordPress site is set up, inside the root of the WP install, create a directory that will hold your React site.
Create React App
The quickest and easiest way to get started with creating a React app is to use Create React App. After installing Create React App, in terminal, cd into your directory that you just made for your React app and run the command create-react-app. The structure of your app will be set up in a matter of moments.
RESTfully get content to your React App
Now that you have your app structure set up, you can start making request to your WordPress site using the REST API. For an idea on how to do this, you can use this sample code to pull your most recent posts into your site.
// App.js file
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
posts: []
}
}
componentDidMount() {
let dataURL = "http://yoursite.dev/wp-json/wp/v2/posts";
fetch(dataURL)
.then(res => res.json())
.then(res => {
this.setState({
posts: res
})
})
}
render() {
let posts = this.state.posts.map((post, index) => {
return
{post.title.rendered}