How to Create a Headless WordPress Site with ReactJS

Table Of Content

Introduction

There may be many people out there who told you to choose WordPress because it is the best CMS out there and it’s free, but let me tell you some crazy statistics about WordPress which will force you to choose WordPress. WordPress’s global content management market share is 64.4%, and over 60 million people chose WordPress to power their website or blog. And if these stats don’t intrigue you, let me tell you that even Beyonce has her website on WordPress. And wait, did I tell you that even Jay Z and Sylvester Stallon also have websites on WordPress.

And what if I tell you that you can use WordPress with one of the best JavaScript libraries out there, ReactJS, which is developed by Facebook and is used by Uber, Airbnb, Dropbox, and not only that, even Asana is made with ReactJS. 

Now I know what your next question will be, but how to do that? The answer is simple, with the help of Headless WordPress. With Headless WordPress, you can use WordPress and ReactJS together and build one of the best sites out there. 

But let’s first understand what Headless WordPress is?

What is Headless WordPress?

Every website, regardless of its configuration, has a front end and a back end. The front end is how visitors interact with your website. What you’re looking at right now is what a front-end means.

The backend is where the website is managed, including the creation and publication of pages and blogs, the customization of the design and settings, and the addition of additional capabilities via plug-ins.

When the front end and back end are used in unison, this is referred to as a coupled CMS (content management system) architecture. This allows everything to be maintained in a single location, such as WordPress, which is perfect for entrepreneurs, bloggers, and business owners.

Because of the “headless” architecture of the website, the platform’s front end is canceled, leaving only the back end and the API running on the server side.

Naturally, you will be able to continue creating, changing, uploading, and organizing material in the same way you would if you were using a connected system. The difference is that you will access your resources using a different front-end solution referred to as REST API.

This enables the now-headless CMS system to be used universally, regardless of the “language” used to construct the site’s front end. Consequently, you will no longer be reliant on WordPress to display your material on the internet.

Let’s dive into some technical aspects of what a Headless WordPress is, now that we understand what it is.

With the help of Rest API which allows the developers to interact with cross-technology interfaces as long as both of them are speaking the JSON language. The data that comes out with the help of Rest API is in JSON format, and JSON is the most loved format known by almost every web technology. JSON is a text-based representation of JavaScript objects which contains data in key-value pairs.

"names": [
     {
       "id": 0,
       "name": "John Doe"
     },
     {
       "id": 1,
       "name": "Richard Lindley"
     },
     {
       "id": 2,
       "name": "Jack Moore"
     }
   ],

The Benefits of Using Headless WordPress CMS

It can be used on a wide range of devices, such as tablets, PCs, and smartphones. This method helps make your website more accessible. As a headless CMS, WordPress makes it easier to manage and less heavy. You can change the look and feel of your website to make it easier for people to use. When WordPress is used with the new integrated technologies, it is very stable and very fast. This means your website should be able to change in terms of how it works, how big, and how small it is. A headless WordPress powered by React allows the platform’s needs and updates to change over time. It is a must-have service on all internet platforms. So, hire ReactJS developers to make sure your website is safe from internet threats.

How to Set Up a WordPress Site with ReactJs

How to setup WordPress with ReactJs

Let’s begin with setting up the WordPress site, as this will act as a data source for our front-end ReactJS application.

Rest API will be enabled by default. If you want to restrict the Rest API access then you can use Basic-Auth or Oauth2 authentication method

Go to Settings → Permalinks and select either Post name or Custom Structure.

Headless WordPress Setup

Due to the fact that we will be interacting with APIs, download the chrome extension for Postman. Once the Postman is installed, open it and enter the following URL:

https://example.com/wp-json/wp/v2/posts

If you enter the above URL, it will retrieve the post data that is inside your WordPress website.

Code of Headless with React

Getting Started with React

Getting Started with ReactJS

What is ReactJS

React.js is a JavaScript framework for the front end developed by Facebook. Our team uses React to quickly and efficiently build reusable user interfaces with declarative code in a predictable and efficient manner. It is a free and open-source component-based framework for designing the application’s display layer.

  • According to the Model View Controller (MVC) architecture, ReactJs is responsible for mobile and web applications, with the view layer in control of these applications.
  • Its capacity to construct single-page applications and mobile applications is well-known, and it has gained popularity in recent years.

Setting up React App

To build React apps, you need to have the following dependencies installed on your computer.

  • NodeJS & NPM.
  • Text Editors such as Sublime or Visual Studio Code.
  • Git for version controlling (Optional).

After setting up the environment, open the command line and run the following code to create the project with ReactJS.

npx create-react-app frontend

Once the application has been created, cd (change directory) to the application folder, and then type the following command on the command line to install the Axios package for API calls.

npm i axios

Go to your favorite text editor and open the folder. I am using Visual Studio Code.

Launch the application by running the command

npm start

Our web application will be built with React using WordPress as a headless CMS if everything goes according to plan.

Create a new folder components’ inside the src folder, and inside the components folder, create a new file Posts.js.’

How to Render Post Data on ReactJS

Inside the Posts.js file, we will fetch the data from the WordPress Rest API. Below is the code that requests the Rest API end-point – which in my case is /posts– and displays the data in JSON format.

import React, { Component } from 'react'
import axios from 'axios';

export class Posts extends Component {
   state = {
       posts: [],
       isLoaded: false
   }

 componentDidMount () {
 axios.get('https://example.com/wp-json/wp/v2/posts/')
       .then(res => this.setState({
           posts: res.data,
           isLoaded: true
       }))
       .catch(err => console.log(err))
   }


   render() {
       const {posts, isLoaded} = this.state;
       return (
           <div>
               {posts.map(post =>
               <h4>{post.title.rendered}</h4>
               <p>{post.content.rendered}</p>
               )}
           </div>
       );
   }
}
export default Posts

The above code will show the post title and post content.

Now, inside the App.js file, call the Posts component as shown below.

import React from 'react';
import './App.css';
import Posts from './components/Posts';
function App() {
 return (
   <div className="App">
    <Posts/>
   </div>
 );
}
export default App;

App.js is the entry point of our web application. Therefore, it is important to reference the “Posts” components inside this file.

Summary

WordPress and React both have a large community and provide a wide range of features. By using React with Headless WordPress, you will notice a significant improvement in the performance and speed of your website. Additionally, it makes redesigning easier and improves the security of your WordPress site, however, it can be confusing and can be a bit complicated.

Fortunately, there are a number of experienced, knowledgeable developers available that will help you to build a headless WordPress website using React as a front-end technology.  Our development team is constantly keeping up with progress in WordPress development and React JS Development, which helps you to design and develop beautiful mobile and web apps and provides you with the most suitable and comprehensive solutions for your project. Also, be sure to learn more about How to Create a Headless WordPress Site with Vue.js.

author
Vish Shah is Technical Consultant at WPWeb Infotech since 2015. He has vast experience in working with various industries across the globe. He writes about the latest web development technologies and shares his thoughts regularly.

Leave a comment