This post was submitted by Manjunath M as part of our ongoing initiative to feature our community’s staggering wealth of knowledge through high quality blog posts. If you’d like to become a contributor please review our submission guidelines and get in touch.


For over 15+ years now, WordPress has been the most popular and complete CMS solution that lets you build anything from a single-page portfolio to a full-fledged eCommerce platform. WordPress uses PHP for all its backend infrastructure like updates, APIs, auth, DB layer and most of the frontend. However, like other popular frameworks, WordPress has also been forced to evolve in recent times.

Given the rising potential and power of JavaScript applications for web, as well as desktop and native mobile applications, the WP REST API attempts to bridge the gap between the legacy of WordPress’ PHP core and the rise of JavaScript. I believe that this is a huge step for WordPress for two reasons:

  1. Existing WP websites can use React/Vue or another frontend library to create a better UI experience.
  2. Conversely, web developers get an industry standard headless CMS that can be easily integrated with the stack of their choice.

That’s a win-win situation for everyone. In this article, we’re going to focus our energy on building a React frontend for the WordPress backend. But first, let’s have a look at the WordPress REST API.

WordPress REST API Basics

The development of the WP REST API began a few years ago and was initially designed as a standalone feature plugin. WordPress v4.4, codenamed ‘Clifford’, introduced the actual infrastructure of the REST API into the core of WordPress. The actual endpoints made an appearance in WordPress v4.7, codenamed ‘Vaughan’. The WP API lets you use WordPress as a headless CMS that’s easy to use and stable and JSON-friendly.

JSON

JSON is the preferred format if you’re going to integrate WordPress with a JavaScript stack. JSON is similar to XML in that it gives us the ability to efficiently transfer data using a very readable syntax.

JSON is actually a string that comprises a text-based representation of a JavaScript object. It stores data in a set of key-value pairs. A simple JSON example of a WP post can look like this –

{
id: 1,
"title": {
"rendered": "Hello World"
  },
  "content": {
"rendered": "Welcome to WordPress. This is your first
post. Edit or delete it, then start blogging!"
  }
}

A complete JSON response using the WP REST API usually includes additional information regarding the post, like metadata. You have everything you need to create a front-end theme or a plugin to your application.

The End Points

WordPress endpoints are very accessible to the public. If you’re running the latest version of WordPress, you need to simply append /wp-json/wp/v2 to the end of the URL. For instance, you can access the basic endpoints at 127.0.0.1/wp-json/wp/v2 if you’ve set up a WordPress instance in your localhost. If you want to prettify the output, you can use a JSON viewer extension that makes the JSON look pretty on your browser.

The data that’s being displayed on your screen is essentially the content as well as meta information in JSON format. What you have done here is to define a route and asked your browser to fetch the data for you.

What do we mean by route? A route is a URL mapped to a particular method. The WordPress core reads through the route and understands that every ‘/’ represents a specific path or parameter that needs to be followed.

For example, an endpoint can be ‘/wp-json/wp/v2/posts/1’, where you’re requesting for a post with an id equivalent to 1. WordPress APIs are useful because they are pretty extensive. This translates into the ability to take any data from your website and turn it into an endpoint. Almost all the core functionalities in WordPress are supported and all the upcoming features will also be supported. Here is a list of WordPress APIs supported at the moment of writing this tutorial:

Resource Base Route
Posts /wp/v2/posts
Post Revisions /wp/v2/revisions
Categories /wp/v2/categories
Tags /wp/v2/tags
Pages /wp/v2/pages
Comments /wp/v2/comments
Taxonomies /wp/v2/taxonomies
Media /wp/v2/media
Users /wp/v2/users
Post Types /wp/v2/types
Post Statuses /wp/v2/statuses
Settings /wp/v2/settings

Theme developers, as well as plugin developers, can create custom endpoints for their application. If you want to check out all the different endpoints available, you can download an application like Postman. This will provide you with a GUI specially made for exploring APIs. Moreover, you can directly make API calls to third-party apps without having to rely on plugins.

Let’s take an example. Uploading files and maintaining multiple versions of it is an integral requirement to any modern web application. This is particularly true in the case of media files. In WordPress, there is an abundance of plugins available that can do this for you; however, you might need to make calls to the WordPress server to use them.

With WP API, the media-handling logic can be abstracted away from WordPress. You can make all the third-party API calls directly from the frontend which is great in terms of separation of concerns. You can use a library like Cloudinary to manipulate the images and other media files on the fly and then upload them to the cloud. Once uploaded, the URL to the image can be stored in the WP backend. The options are endless and you can combine the pieces together any way that you see fit.

Let’s now see how to connect the WordPress backend with React.

Getting Started with React

React is a declarative front-end library for building user interfaces and interactive applications on the web. With React, you can compose smaller independent pieces of reusable code known as components. Let’s create our first component by creating a React project.

The most popular way to create a React project is by running create-react-app. CRA offers a comfortable environment for learning React and is the best way to start building a new single-page application if you’re a beginner. It sets up your development environment so that you can use the latest JavaScript features such as ES6, and webpack. Moreover, create-react-app provides a nice developer experience and optimizes your app for production.

getting-started-with-react

You’ll need to have Node >= 8.x and npm >= 5.2 on your machine. To create a project, run the following commands:


npx create-react-app wp-react-demo

The above command creates a boilerplate template for our react application which we’ve named wp-react-demo.


cd wp-react-demo
npm start

If everything goes well, it should be able to serve the newly created application on a development server at https://localhost:3000/.

If you’re curious to see the directory structure generated by create-react-app, this is what it looks like:

.
├── README.md
├── package.json
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
├── src
│ ├── App.css
│ ├── App.js
│ ├── App.test.js
│ ├── index.css
│ ├── index.js
│ ├── logo.svg
│ └── registerServiceWorker.js
└── yarn.lock

The public directory contains all the assets required for starting the application. The src directory comprises all the JavaScript files that we will be working on and you’ll be spending a lot of your time there.

When you visit localhost:3000, the index.html file gets loaded. If you open up the public/index.html file, there’s nothing much there. But you will find this line somewhere in the middle:

<div id="root"></div>

That’s the starting point where React renders the component tree into the root of the application.

What does that mean? Head over to src directory and open up index.js.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

React tries to find an element with id “root” in the document and then injects the component into the root. In reality, the App component gets rendered and that’s where the spinning React logo is coming from. You can verify that by opening the src/App.js file.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
 render() {
   return (
     <div className="App">
       <header className="App-header">
         <img src={logo} className="App-logo" alt="logo" />
         <h1 className="App-title">Welcome to React</h1>
       </header>
       <p className="App-intro">
         To get started, edit <code>src/App.js</code> and save to reload.
       </p>
     </div>
   );
 }
}

export default App;

This is basically what a component looks like. Each component renders a part of your UI. You can compose one component inside another one and that’s how you get a component tree structure like this one:

react-component-tree

If you’re wondering why we’re able to use HTML inside render(), that’s the magic of JSX. JSX is a syntax extension to JavaScript and lets you use plain HTML in a JavaScript file. You can read more about it in the official docs.

I am going to delete all the HTML content and then replace it with a

tag like this one:

<div>
<h2> WordPress Blog </h2>
</div>

React Components and State

Components are the building blocks in React. Each component can have

  1. an input (or multiple inputs) commonly known as props.
  2. a state that’s local to the component
  3. methods that either render something ( for eg: render()) or handle some business logic

We’ll build a component that will retrieve all the available posts and display them back to the user. To do that, we’ll first write a constructor for the class and initialize the state in the constructor:

constructor (props){
   super(props);

   this.state = {
     title: {},
     date: "",
     content: {}
   };
 }

The state is a JSON object. We’ve declared a title, date, and content properties inside the constructor. The title and content are objects whereas date is an array.

Fetching the Data and Updating the State

Now, when the component mounts, it needs to fetch the posts data from the API and store it in the state. The posts data is available in the following URL:


https://localhost/wp-json/wp/v2/posts/

So, where do we put this logic? The constructor might sound like a good choice because it gets invoked when the component is created, but it’s not the best choice. Instead, we’re going to use something known as a lifecycle method. The componentDidMount() lifecycle method gets called after the component has mounted.

componentDidMount() {
       return fetch(`https://wordpress.com/wp-json/wp/v2/posts/`)
       .then((response) => response.json())
       .then((responseJson) => {
        // Update state here         
       })
       .catch((error) => {
         console.error(error);
       });         
 }

We’re using fetch which is the de-facto standard in JavaScript for making API calls. The parameter to fetch() is the URL that we want to fetch. Fetch returns a Promise which we can evaluate by a chain of .then()s. The first then block converts the response to the json format so that we can place it in the state.

const { title, date, content } =  responseJson;

        this.setState({ title, date, content });

So, what happens here? First we extract the title, date and content fields from the responseJson object. The weird syntax that you see here is known as destructuring assignment syntax. As you might already know, the WP API returns a lot of information that we don’t require. The destructuring assignment syntax makes it possible to unpack values from the object into distinct variables.

Next, we use this.setState() to update the component’s state. The setState() method accepts an object as a parameter which is going to be the updated state.

Rendering Our WordPress post

The render method returns JSX that we discussed earlier. Unlike pure HTML, you can actually embed expressions into JSX. For instance, if you need to render the title of the fetched post and nothing else, you can do this:

render() {
   return (
     <div>
     {this.state.title.rendered}
     </div>
   );
 }
}

Try it!

Similarly, you can render the date by embedding {this.state.date}. However, the content stored in the state comprises actual HTML. Since the HTML is returned from the server, it’s safe to assume that there is no danger in rendering it. So, to render the content, you will need to dangerouslySetInnerHTML attribute as follows:

<div
    className= "content"
    dangerouslySetInnerHTML={{ __html: this.state.content.rendered }}>
</div>

Here is the render() method in action.


render() {
   return (
     <div>
       <div>
             <div className="row">
               <div className="leftcolumn">
                 <div className="card">
                   <div className= "title">
                     <h1>{this.state.title.rendered}</h1>
                     <p> {this.state.date} </p>
                   </div>
                
                   <div
                     className= "content"
                     dangerouslySetInnerHTML={{ __html: this.state.content.rendered }} />
                 </div>
               </div>
             </div>
           </div>
     </div>
   );
 }
}

I’ve added some extra tags and classes for styling. You can write all your styles in a file in the src directory and import it into your App.js. You can find the styles for this project at src/App.css. Don’t forget to add an import statement, otherwise the styles wont work.

import './App.css';

That’s it. You’ve created a basic front-end for your WordPress API backend using React. This is what the default Hello World post should look like in our application:

basic-wordpress-react-app-final-result

Summary

Phew! That’s a lot of ground covered in a single day. We started off with WordPress Rest API and then familiarized ourselves with the API endpoints. We then started building a React application from scratch that basically displays a WordPress post.

Using React with WordPress is just the same as using React with any other backend API. With WordPress, it’s more easy to find data and you know exactly where to look. If you’ve just started exploring React, I’d recommend React docs as a good place to get started. If you have any questions, feel free to ask in the comments.

The post React JS for WordPress Users: A Basic Introduction appeared first on Elegant Themes Blog.