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 March 1, 2024

11 Min Read
wordpress react

Headless WordPress has emerged as a transformative approach to web development, revolutionizing how content is managed and presented online. Headless WordPress decouples the content management system (CMS) capabilities of WordPress from the frontend presentation layer, empowering developers to wield unparalleled flexibility and creativity in crafting user experiences.

With rapid advancements in web development technologies, the traditional coupling of backend and frontend often hinders the adoption of new tools and frameworks. Headless WordPress ensures that content remains accessible and adaptable to emerging trends and technologies.

Headless WordPress represents a shift in CMS and web development, offering flexibility, and scalability at same time. By decoupling the backend CMS from the frontend presentation layer, Headless WordPress empowers developers to create dynamic, interactive, and highly customizable digital experiences that transcend the limitations of traditional WordPress setups.

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.

Headless vs Decoupled CMS – Learn the Difference

Headless CMS and Decoupled CMS are two architectural approaches to content management systems that offer more flexibility and agility compared to traditional monolithic CMS setups. Here’s a breakdown of the differences between the two:

Aspect Headless CMS Decoupled CMS
Frontend Flexibility Provides maximum flexibility for frontend development. Provides some flexibility but is tied to a specific frontend technology.
Backend Independence Completely separates the backend (content management) from the frontend. Decouples the frontend presentation layer but still relies on the CMS for backend functionality.
Technology Agnostic Allows the use of any frontend technology e.g., React, Angular, Vue.js. Often comes with predefined frontend technologies or frameworks.
Performance Typically offers better performance as content is served directly to the frontend without rendering overhead from the CMS. May experience performance bottlenecks due to tight coupling between backend and frontend.
Scalability Highly scalable as it allows you to scale frontend and backend independently. Scalability may be limited due to the coupling between backend and frontend.
Development Speed Speeds up the development process by allowing frontend and backend teams to work concurrently. Development may be slower due to dependencies between frontend and backend teams.
Content Syndication Enables content syndication across multiple platforms and channels easily. Content syndication may be more challenging due to the coupled architecture.

How to Set Up ReactJS with Headless WordPress

Setting up ReactJS with a headless WordPress setup involves decoupling the front end (ReactJS) from the back end (WordPress) and using WordPress as a content management system (CMS) only.

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 fully managed web 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.

Experience the power of Headless CMS architecture with Cloudways’ optimized hosting solutions.

Take control of your technology stack and choose any frontend framework or technology while enjoying the reliability and performance of Cloudways’ managed cloud hosting.

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.

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)

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.

Pre-Requisites

Make sure 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)

How to Create a 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.

Headless WordPress CMS – Benefits and Drawbacks

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.

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.

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.

Q. Can you use React with WordPress?

A: 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. Is Headless WordPress more secure?

A: 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?

A: 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. Who Should Use Headless WordPress?

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

Q. What are the limitations of headless WordPress?

A: The limitations of headless WordPress primarily revolve around the additional complexity and potential challenges it introduces compared to traditional WordPress setups.

  • Steep Learning Curve
  • Increased Development Time
  • Limited Plugin Compatibility
  • Maintenance Overhead

Q. What is the difference between headless and non-headless WordPress?

A: In a non-headless WordPress setup, the CMS controls both content management and frontend rendering, meaning that content creation and display are tightly coupled within the WordPress ecosystem.

Whereas, a headless WordPress setup decouples the CMS from the frontend, serving content exclusively through APIs.

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