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.

ūüď£ Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW ‚Üí

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

Updated on October 26, 2023

10 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.

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.

Experience Unmatched WordPress Performance

Leverage the power of Cloudways WordPress Hosting with a WordPress-optimized stack, automated backups, and SSH access to supercharge your website’s performance and security.

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. Let’s begin;

Step 1: Choose the Hosting Provider

Choosing the right WordPress hosting platform is the first and crucial step when setting up WordPress and creating a headless CMS.

Hosting plays a pivotal role with headless WordPress because even though the “head” (the front end) is detached in a headless approach, the “body” (the back end) still resides on a server that needs hosting.

The server’s performance, security, and reliability are critical to ensure that the content gets delivered smoothly to the front end, regardless of the technology used.

Therefore, choosing a host that offers optimum server performance and enhanced security helps. Considering that, I would recommend Cloudways because it offers the perfect blend of speed, security, and support, ensuring your headless WordPress journey is smooth sailing.

Specifically, Cloudways provides managed hosting on top-tier cloud providers like AWS, Google Cloud, and DigitalOcean, ensuring high-speed performance and scalability. The platform offers one-click installations, making the setup of WordPress and other tools hassle-free.

Also, With built-in advanced caches and a content delivery network (CDN), your content gets delivered faster, irrespective of the user’s location.

Additionally, Cloudways ensures robust security through regular security patching, a dedicated firewall, and SSL installation, helping protect your backend data and interactions. Automated backups and easy restore options provide an added layer of data protection and peace of mind.

Furthermore, Cloudways’ 24/7 customer support and extensive knowledge base ensure that any issues you encounter are swiftly addressed, allowing you to focus on building and managing your headless CMS without any hosting-related hassles.

Step 2: Enable WordPress Rest API

  • First, download the zip file of the WP-Rest API plugin from git.
  • Upload the zip folder inside your WordPress plugins folder.
  • Once the file is uploaded, activate the plugin to enable WordPress Rest API.

Step 3: Fetch Post Data

To fetch the post data, follow these steps:

  • 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

Step 4: Create Custom Post Types

To create custom post types:

 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.

Step 5: Check and Verify

  • 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.

What Is React & How to Set it Up

JavaScript is a powerful tool for web development and React is a JavaScript library for the web maintained by Facebook and the developer community.

ReactJS is mainly used to develop single-page applications that are fast, robust, and dynamic.

No More Management Hassles with Managed WordPress Hosting

Set yourself free of all hosting-related tasks and get boosted performance results with Cloudways WordPress hosting. 3-day free trial (no credit card required)

How to Set Up React

Pre-Requisites

Ensure you have the following dependencies installed on your computer before building React apps.

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

Create Project with ReactJS

  • 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

Here’s how you can display post data on ReactJS

  • Add the code below 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.

The Benefits and Drawbacks of Using Headless WordPress CMS

Now that you know how to create the headless WordPress CMS, you must know the potential benefits and drawbacks of having it.

Benefits of Using Headless WordPress

The first and the most important benefit that you have with using headless wordpress CMS is the flexibility it offers. With the headless approach, you have the freedom to pick and design any face (or front-end) you want, using modern technologies. It makes your website faster, more responsive, and precisely tailored to your users’ needs.

Not just this, your website is more secure because when the front is seperated from the back, there’s little chance of bad actors messing with your content.

Drawbacks of Using Headless WordPress

As for the drawbacks considered, the headless wordpress CMS is complex. Traditional WordPress setups allow you to use themes and plugins that integrate easily.

Also, going headless means you might miss out on some of these integrated features, and you’ll need to put an extra effort into reinventing the features.

And for smaller teams and newbies managing two separate systems can be tiring since it’ll require you to handle updates, compatibility checks, and fixes for both the CMS and the front end.

Wrapping Up!

In conclusion, using WordPress with React to create a headless CMS for your web application opens up a world of possibilities for developers and content creators alike. By decoupling the front end and back end, you gain the flexibility to design a user interface with React’s powerful features while managing content seamlessly through WordPress.

Throughout this blog, we’ve walked you through the essential steps, best practices, and useful tips to integrate these two robust technologies, ensuring a smooth and efficient development process.

Achieve Unrivaled Performance with Cloudways Headless CMS Hosting

Our headless CMS hosting amplifies your React app’s performance by 5x, backed by a robust security infrastructure.

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, making it a popular choice among JavaScript 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.

Q. Are there any plugins or tools available to help integrate React with WordPress?

Yes, plugins like WPReactivate help to integrate React with WordPress. React WordPress enables a React-powered frontend, while Gutenberg facilitates custom React-powered blocks. Additionally, Create React App aids in building standalone React applications within WordPress.

Q. Can I still use WordPress themes and plugins with a React-based headless CMS setup?

Yes, you can use WordPress themes and plugins with a React-based headless CMS setup. In a React-based headless CMS setup, WordPress continues to serve as the content management system. WordPress themes and plugins can be utilized for content management, while the React-based frontend consumes the content through APIs.

Q. Should you use a headless WordPress Website?

Yes. You should use headless WordPress if you prioritize flexibility in front-end technologies and enhanced performance.

Q. Who Should Use Headless WordPress?

Developers and businesses seeking advanced customization and integration with modern web frameworks should use headless WordPress.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Mansoor Ahmed Khan

Passionate about technology, entrepreneurship, and marketing, Mansoor Ahmed Khan is in computing since he knows how to type on a keyboard. His daily life is rocked by his family, projects, and his screen. Probably in this order, he likes to be convinced at least. You can reach out to him at [email protected].

×

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!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now