This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Calculate Your Savings on Cloudways and Compare With Kinsta, WP Engine and Flywheel. Calculate Now

Use WordPress with React to Create Headless CMS for Your Web Application

Updated on November 9, 2022

8 Min Read
wordpress react

WordPress Rest API is one of the many great features WordPress offers. It enables developers to create fascinating plugins and themes and allows them to power third-party applications with WordPress CMS.

The content management system is also developed to manage the website’s content in modern web applications. This can add an extra workload for the developers. With so many possibilities that Rest API offers, one can also think of using WordPress with React as a headless CMS for their JavaScript-based web application(s).

What Is Headless WordPress?

A headless WordPress website is a site that mainly uses WordPress for content management and uses any other technology to build the front-end and display the content to the website visitors.

Managed WordPress Hosting Starting From $10/Month

Enjoy performance boosts, and manage your sites easily with the intuitive Cloudways platform.

Rest API allows developers to interact with cross-technology interfaces as long as both speak the same language of JSON. WordPress Rest API spits out data in JSON format, which is understandable by a large number of web technologies. JSON is a text-based representation of JavaScript objects which contains data in key-value pairs.

"friends": [
      {
        "id": 0,
        "name": "Harriet Stanley"
      },
      {
        "id": 1,
        "name": "Benton Odom"
      },
      {
        "id": 2,
        "name": "Jackie Edwards"
      }
    ],

Today, I will demonstrate the power of WordPress Rest API by using it with React and WordPress as a headless CMS for my basic web application.

The Benefits of Using Headless WordPress CMS

Being an open-source platform, WordPress offers great flexibility to create any website. Using WordPress as a headless CMS allows you to create the front-end of your web application using any web technology and manage its content using one of the most popular CMS.

You might come across the situation where you need to add a blog feature in an existing web app built with either React or Angular. Instead of coding the full-fledged content management system in the native framework, use headless WordPress CMS to manage the content using Rest API. You can make use of this feature using managed hosting for WordPress also.

WordPress Site Speed Matters!

More loading times = Fewer conversions
Get our Ebook to get acquainted with the shocking factors that decrease your site’s speed.

Thank You

Your Ebook is on its Way to Your Inbox.

How to Set Up a WordPress Site for ReactJS

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

Download the zip file of the WP-Rest API plugin from git and upload the zip folder inside your WordPress plugins folder. Once the file is uploaded, activate the plugin. This will enable WordPress Rest API inside your WordPress website.

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

wordpress permalinks

Since we are working with API calls, download the chrome extension for Postman. Inside the Postman, enter the URL in the following format:

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

The above URL will fetch the posts data inside your WordPress site.

source code

Download the Custom Post Type UI plugin for creating custom post types. This custom post will be displayed when we use WordPress with React in the next step.

custom post type UI

Install and activate the plugin and add a new post type. For this tutorial, I will be creating a custom post type for Books.

CPT UI settings

Inside the Post Type Slug, type the name of your custom post.

custom post UI api setting

Ensure that Show in REST API checkbox is set to true and REST API base slug is also set. This is mandatory if you wish to use WordPress as headless CMS.

custom post type support list

Check all the boxes for the information you seek to get from the REST API.

After saving the changes, you will notice that a new option is populated in the sidebar. Click on it to add the new Book inside your custom post type.

I created my first book by putting in the sample data and an excerpt for my post.

To verify that the data is available via API, go ahead and hit the URL inside the Postman.

Now, the URL should look something like https://exampe.com/wp-json/wp/v2/books.

We can also add further fields like Publisher by using ACF and ACF to RestAPI plugins.

advance custom fields

Install and activate both plugins.

acf to rest api

By default, ACF does not speak to the WordPress Rest API. Therefore, we need to download the ACF REST API plugin as well.

add wordpress custom fields

Using the custom fields plugin, I will add the Publisher field for my books.

Make sure to select the desired post type from the list. After that, hit ‘Publish.’

A new field is populated inside my custom post type where I can define the publisher of my book. That’s all we needed to do to set up our WordPress for sending our data to our ReactJS web application.

300x Faster WordPress Websites on Cloudways

Move it to Cloudways Using Our Free Migration Plugin

Getting Started with React

What’s ReactJS

React is a JavaScript library for the web maintained by Facebook and the developer community. JavaScript is a powerful tool for web development, and there are several libraries written in JavaScript to enhance the functionality of the websites. ReactJS is mainly used to develop single-page applications that are fast, robust, and dynamic.

Setting up React App

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

  • NodeJS & NPM.
  • Text Editor 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 app is created, cd (change directory) to the application folder and type the following command to install the Axios package for API calls.

npm i axios

Now, open the folder inside your favorite text editor. I am using the Visual Studio Code.

Launch the application by running the command npm start.

We are all set to build our web application with React using WordPress as headless CMS if everything works properly.

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

How to Render Post Data on ReactJS

Inside the Book.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 ‘/books’ – and displays the data in JSON format.

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

export class Books extends Component {
   state = {
       books: [],
       isLoaded: false
   }

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


   render() {
      console.log(this.state);
       return (
           <div>
              
           </div>
       )
   }
}

export default Books

The above code will show the array of data in the console, which is then utilized inside the render block.

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

import React from 'react';
import './App.css';
import Books from './components/Books';

function App() {
 return (
   <div className="App">
    <Books/>
   </div>
 );
}

export default App;

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

How to Display Post Data on ReactJS

The data can be displayed by adding the code inside the render method.

render() {
       const {books, isLoaded} = this.state;
       return (
           <div>
               {books.map(book =>
               <h4>{book.title.rendered}</h4>
               )}
           </div>
       );
   }

Instead of displaying data here, we will create a new component and name it ‘BookItems.js’ as I want to keep it separate from the parent component.

Change the render method inside Bookk.js to something like:

render() {
       const {books, isLoaded} = this.state;
       return (
           <div>
               {books.map(book =>
               <BookItems key={book.id} book={book}/>
               )}
           </div>
       );
   }

Now, we need to render the BookItems component instead.

Inside the BookItems.js, add the following code:

import React, { Component } from 'react'
import axios from 'axios';
import PropTypes from 'prop-types';

export class BookItems extends Component {
 
   render() {
       const { title } = this.props.book;
       return (
           <div>
              <h2>{title.rendered}</h2>
           </div>
       )
   }
}

export default BookItems

In the code above, I’m referencing the book prop to get the title and other information.

Note: Make sure to reference the BookItems component inside the “Books” component.

My final version of BookItems.js looks something like this:

import React, { Component } from 'react'
import PropTypes from 'prop-types';
import axios from 'axios';
export class BookItems extends Component {

   state = {
       imgUrl: '',
       author: '',
       isLoaded: false
   }

   static propTypes = {
       book: PropTypes.object.isRequired
   }

   componentDidMount () {
       const {featured_media, author} = this.props.book;
       const getImageUrl = axios.get(`https://wordpress-179008-1030625.cloudwaysapps.com//wp-json/wp/v2/media/${featured_media}`);
       const getAuthor = axios.get(`https://wordpress-179008-1030625.cloudwaysapps.com//wp-json/wp/v2/users/${author}`);
      
       Promise.all([getImageUrl, getAuthor]).then(res => {

           console.log(res);
           this.setState({
               imgUrl: res[0].data.media_details.sizes.full.source_url,
               author: res[1].data.name,
               isLoaded: true

           });
       });
    }
 
   render() {
       const { title, excerpt } = this.props.book;
       const {author, imgUrl, isLoaded} = this.state;
       return (
           <div>
              <h2>{title.rendered}</h2>
              <img src={imgUrl} alt={title.rendered}/>
              <strong>{author}</strong><br/>
              <div dangerouslySetInnerHTML={{__html: excerpt.rendered}}></div>
           </div>
       )
   }
}

export default BookItems

And the output in the browser looks like this:

Not the prettiest one, right? Well, that’s because styling is out of the scope of this tutorial.

Wrapping up!

Today, I have shown you how to use WordPress with React as a headless CMS for your web application. The React code is also available on Git for you to download. However, It is not limited to React. You can also experiment with VueJS, Angular, or any JavaScript framework. There are tons of things you can do with WordPress Rest API. The sky’s the limit, so go ahead and use WordPress for your next web project.

Q. What is headless WordPress?

When WordPress is used as a CMS to manage only the content of a decoupled front-end web app, it is known as a WordPress headless CMS.

Q. What is React?

React is a JavaScript library maintained by Facebook and community developers. It is used to build the user interface of modern web applications.

Q. Can you use React with WordPress?

Yes, React can be used with WordPress, as in the example above, where the content on the front-end built with React is managed by WordPress CMS using the WP Rest API.

Q. Can WordPress be used as a headless CMS?

WordPress is the most flexible CMS that allows you to create almost any type of website. Its open-source nature means that you can use WordPress as a headless CMS.

Q. Is Headless WordPress more secure?

Yes, to some extent, headless WordPress makes your website more secure as hackers cannot access your backend.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Beautifully optimized hosting for WordPress and Magento”

Arda Burak [Agency Owner]

Ibad Ur Rehman

Ibad Ur Rehman is a WordPress Community Manager at Cloudways. He likes to explore the latest open-source technologies and to interact with different communities. In his free time, he likes to read, watch a series or fly his favorite Cessna 172SP in X Plane 11 flight simulator.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Unleash The Cloud.
Not Budgets.

For 4 Months +
Up To 30 Free Migrations

Cyber Week

SAVINGS
Time Left In Offer
  • 0

    Days

  • 0

    Hours

  • 0

    Minutes

  • 0

    Seconds

40% OFF

On All Plans

GET THE DEAL NOW