Written by 7:49 pm Wordpress

WordPress with React to Create Headless CMS for the Web Application

17 Shares

WordPress offers many great features, and one of them is the Rest API. It can be used by developers to create plugins and themes. The third-party applications can also be integrated into WordPress CMS through Rest API when you hire WordPress developers for your project.

Using WordPress as a headless CMS with React is becoming common day by day for JavaScript applications since it eliminates the need to develop a content management system for a modern web application. This makes the development and deployment process way too quick.

What Is Headless WordPress?

A Headless WordPress is a website that uses WordPress as a CMS and another technology for its front-end development. The content that visitors will see would be created by another technology, whereas the content managed at the back end would be executed via WordPress.

Once again, it is made possible by WordPress’s Rest API. If cross-technology interfaces are using the same language of JSON (JavaScript Object Notation), it will allow developers to interact. Fortunately, the JSON format of Rest API is understandable by many of the technologies today. The data is stored in key-value pairs in JSON.

“friends”: [

{

“id”: 0,

“name”: “Siddharth Pratik”

},

{

“id”: 1,

“name”: “Nikhila Usha”

},

{

“id”: 2,

“name”: “Sunil Gopal”

}

],

Apart from Rest API, one can also use GraphQL API for WordPress. Using this Rest API with React, you can create a basic web application. Before we get into setting one up, let’s understand what’s the difference between a traditional CMS and a Headless CMS.

Traditional Vs. Headless CMS

How is a headless CMS different from traditional CMS?

Traditional CMS

Traditional CMS

Here, there would be a combination between CMS and your site’s design. The site design includes CMS as well, and that makes it easier to update the content without having to manually update the pages via HTML, moving it and the other files with FTP, etc. CMS like WordPress and Drupal connect front-end and back-end with an easy codebase, from database to presentation layer.

Pros of Traditional CMS

  • The whole website is served from a single system.
  • Content management is easy.
  • Themes and templates can help you control the front end.
  • Available with great community support.

Technical barriers are low for entry-level developers.

Cons of Traditional CMS

  • Only website content is created, and not usable for other devices.
  • Scalability is questionable.
  • CMS-specific developers are required.
  • Flexibility is limited.
  • Maintenance and expansion can be expensive and time-consuming.

Traditional CMS can be used when you only want a website for your project, for small businesses, or for enterprises that need not share content on other digital properties. It can be up and running in a blink, and the management can also be done from a single source. Many traditional CMS also have plugins to solve a number of challenges and benefits.

Headless CMS

Headless CMS

As we learned earlier, a headless CMS will not connect directly to the front end. Where traditional CMS was about managing the CMS and front end from a single source, headless CMS only takes care of the content. The content can be created and edited in the CMS, and later will be published with an API. The CMS will have no effect on the front end.

Compared to traditional CMS, this provides more flexibility as you can get your content out in the ways you want, regardless of the presentation style and device.

Benefits of Headless CMS

  • Content can be served on any device
  • Developers can focus more on presentations than on worrying about the content.
  • Preferred frameworks and tools can be used with headless CMS.
  • Creating content without worrying about all of it being in a single system.
  • It offers fast, secure, and reliable static websites.
  • Managing and tracking changes in the content is easy.

Cons of Headless CMS

  • Not all of them offer a content preview. It can enable you to build a preview integration but does not add additional upfront overhead.
  • More upfront integration and configuration efforts are required.
  • You will need to develop both the content and the presentation layer separately, sometimes with different technologies for different devices.

That’s the difference between a traditional CMS and a headless CMS. Each of them comes with its own pros and cons, and the selection of the technology will depend on your requirements completely. So when should you use a Headless CMS? Let’s find out.

When To Use Headless CMS?

Since it allows you to share a single content on multiple devices, Headless CMS is the need of the hour with so many presentation options out there. Headless WordPress offers APIs like Rest to make your job even easier. Here are some of the use cases for Headless WordPress projects.

  • If your application or website uses JavaScript frameworks like Angular, React, or Vue JS, headless CMS can benefit you.
  • If you are looking to build native mobile applications.
  • If your project requires publishing content across multiple platforms.
  • If a static site generator is being used.

Now that you know where you can implement it, let’s understand how to set it up.

Setting Up a WordPress Site for ReactJS

Setting Up a WordPress Site for ReactJS

For making a headless CMS for the web application with WordPress and React, WordPress will act as a data source. You can follow the steps below or hire a WordPress developer to set up the WordPress:

  • Download the WP-Rest API plugin zip from the git and upload it to your WordPress plugin folder. Activate the plugin once your file is uploaded.
  • In your WordPress, go to settings, then Permalinks, and select the post name or Custom Structure.
  • You will need to work with the Postman extension for Chrome as we are working with API calls.
  • In Postman, add /wp-json/wp/v2/posts to the end of your WordPress site URL.
  • To create custom post types, you need to download the Custom Post Type UI plugin. When we use WordPress with React, the custom post will be displayed.
  • Now, install and activate the plugin to start adding a new post type. Type the name of your custom post in Post Type Slug.
  • Check the box saying ‘Show in REST API’ and ensure that the REST API base slug is set. This is an essential step for using WordPress as a Headless CMS.
  • You will also need to check the boxes of the information you seek from the Rest API.
  • Save the changes and you will see new options populated in the sidebar. You can start adding your content now in your content type.
  • Once you add sample data, hit the URL in the Postman to see if it’s available through API. The URL will be “https://exampe.com/wp-json/wp/v2/contenttype”

Use ACF and ACF to RestAPI plugins to add other fields to the content type. ACF is not directly compatible with WordPress Rest API, you will need to download ACF REST API, too. In there, add all the custom fields you want to add to your content type.

Once you have added custom fields, hit publish and they will be visible in the custom post type.

That’s all you need to do for setting up WordPress and now we will move on to React.

Getting Started with React

What’s ReactJS?

React is a JavaScript library for front-end development. It is developed and maintained by Meta, and is completely open source. Companies hire React developers for building single-page applications, mobile, and server-rendered applications, it is a preferred choice of many.

The library adheres to declarative programming. A developer will design a view for each state of the application, and it will be updated and rendered in components when the data changes. The components are reusable and they can be rendered to a particular element in DOM with the help of React DOM library.

React Hooks let developers hook into the state and lifecycle features of functional components. Hooks also let you use React without classes. Reconciliation of Virtual DOMs is another notable feature of DOM, which saves you a lot of time when compared to real DOM. Let’s understand all of this in detail.

Benefits of ReactJS

Benefits of ReactJS

Declarative Framework

The declarative DOM of ReactJS adjusts UI when the developer will change the application state, interacting with DOM. With this declarative approach, reading and understanding the code becomes easy. If you plan to add more people to your team in the future or are thinking about collaborating, this will come in handy.

Testing

React keeps the code testable. Developers can analyze the performance of the application with multiple devices with the ability to test the app. It also helps in quick debugging and data tracking, allowing for proper tracking.

SEO Friendly

ReactJs is a lightweight library. It helps you make your apps SEO friendly. This has proven to be extremely helpful with Google’s focus on the core web vitals. The rendering is faster with React, reducing your page loading time and keeping your app SEO-friendly.

Large Community

React is a community-driven technology in many ways. There is large community support available whenever you are looking for it. Sure, the Meta is the one maintaining it, but developers contribute to the community from all over the world.

Mobile-friendly

Cross-platform applications can be made with React. You can develop and release apps for multiple platforms. This will mean an extended reach for your audience if you plan to expand in the future.

Easy Learning

Compared to Ember, Angular, and Vue, React is far easier to access. An approachable learning curve is something that attracts many developers to React and helps them stay with the technology. It is adaptable, easy to learn, has a large community, and stays and maintains the project in the long run.

Reusability

As mentioned above, React components can be reused for development. This allows starting your development with reusable tiny code pieces and moving to the larger ones, eventually getting component-based app fundamentals. This saves time for developers and they can focus on other tasks.

Stability

React has a core that is stable and it uses the downward data flow. Even if you tweak the application structure, the elements will not change and you can make amendments as you proceed. The stability makes it reliable for project owners to choose React for their business apps.

Productivity

There are many productivity perks that come with React, and analyzing just one of them can give you a good idea about it. For example, virtual DOM helps you remove heavy foundation processes and leave only the obligatory ones. The reusability of the codes and working with components are all there to help you save your time and boost productivity with fast development.

Diverse Toolset

React provides developers with a strong toolset to work with, optimizing their workload. Compared to other JavaScript frameworks, this one has the richest, most well-rounded, and most diverse toolset for developers to work with.

Now that you are convinced about using React with your Headless WordPress application, Let’s start with setting up the library.

Setting up React App

To make the most of the React framework and set it up, you can hire a React Developer. To set up React, we first need to install the following dependencies on the computer.

  • NodeJS and npm
  • Code Editor
  • Git (for Version controlling)

Git is optional here but recommended. Once you have set up the environment, now you need to create a project with ReactJS. Open the command line and run the following code:

npx create-react-app frontend

Once you create the app, change the directory to the application folder. To install the Axios package for API calls, type the following line.

npm i axios

After that, you need to open the folder in the text editor. Launch the application by running npm start. If everything runs properly, we are all set to build our web application with WordPress as Headless CMS with React.

How to Render Post Data on ReactJS

Now, you need to create a new folder called ‘components’ in the src folder. Create a new file in there.

Inside that file, fetch the data from WordPress Rest API. Request the Rest API endpoint with the code below and display the data in JSON format. In this example, we have used ‘books’ as the file and content type.

import React, { Component } from ‘react’

import axios from ‘axios’;

export class Books extends Component {

state = {

books: [],

isLoaded: false

}

componentDidMount () {

axios.get(‘https://wordpress-123456-7891011.yoursite.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

This will show the array of data in the console, which will be utilized in the render block.

In your App.js file, call the book components.

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 will be the entry point of your web application. Therefore, it is essential for book components to be referenced inside the file.

How to Display Post Data on ReactJS

Here is the code to display the data inside the render method:

render() {

const {books, isLoaded} = this.state;

return (

<div>

{books.map(book =>

<h4>{book.title.rendered}</h4>

)}

</div>

);

}

Instead of displaying the data here, a new component named ‘BookItems.js’ can be created and you can change the render method inside Book.js like this:

render() {

const {books, isLoaded} = this.state;

return (

<div>

{books.map(book =>

<BookItems key={book.id} book={book}/>

)}

</div>

);

}

Now, render the BookItems component.

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

Here, we are referencing the book prop to get the title and the information. The output in the browser will see the book title, image, author name, and except for the book. You’ve done it!

Conclusion

Here, we have used WordPress with React as a headless CMS for creating a functional web application. There are many benefits of using React with WordPress as a Headless CMS as we have listed above. It also works with other JavaScript frameworks such as VueJS and Angular. The Rest API of WordPress provides developers with endless possibilities. Here are the key takeaways:

  • When WordPress is used as a CMS to manage only the content of the website and not for the front end, it is called a headless CMS.
  • React, a JavaScript framework developed and maintained by Meta can help you build modern UIs.
  • React can be used with WordPress, where the front end is developed with React and WordPress acts as a CMS. WP Rest API connects them both.
  • Using WordPress as a Headless CMS can be beneficial for you in many ways, and the security of the web application is one of the most prominent reasons.

Hope this will help you understand WordPress with React as Headless CMS.

(Visited 234 times, 1 visits today)
Close
17 Shares
Share via
Copy link