WordPress Rest API is one of the many great features WordPress offers. It enables developers to create fascinating plugins and themes, and also allows them to power third-party applications with WordPress CMS.
In modern web applications, the content management system is also developed to manage the content of the website. This can add 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).
So What the Heck Is Headless WordPress?
Being ‘Headless’ definitely does not mean that the CMS is missing the header section. It means that you can use the CMS as a generic content management system irrespective of the technology used to build the front-end.
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 pair.
"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 benefit of Using WordPress Headless CMS
Being an open-source platform; WordPress offers great flexibility to create any kind of 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 WordPress headless CMS to manage the content using Rest API.
Setting up a WordPress Site
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.
Now, go to Settings → Permalinks and select either Post name or Custom Structure.
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.
Download the Custom Post Type UI plugin for creating custom post types. This custom post will be displayed when we will use WordPress with React in the next step.
Install and activate the plugin and go-ahead to add a new post type. For this tutorial, I will be creating a custom post type for Books.
Inside the Post Type Slug, type the name of your custom post.
Make sure 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.
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 as well as 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.
Install and activate both the plugins.
By default, ACF does not speak to the WordPress Rest API, therefore, we need to download the ACF REST API plugin as well.
By 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.
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 apps using React 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.
If everything works properly, we are all set to build our web application with React using WordPress as headless CMS.
Create a new folder ‘components’ inside the src folder, and inside the ‘components’ folder create a new file ‘Books.js’.
Rendering 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 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.
Displaying 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 give reference to 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:
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 it. 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.
Frequently Asked Questions
Q. What is a 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.
Start Growing with Cloudways Today!
We never compromise on performance, security, and support.
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.
Keep reading the article at The Official Cloudways Blog. The article was originally written by Ibad Ur Rehman on 2020-02-18 00:28:37.
The article was hand-picked and curated for you by the Editorial Team of WP Archives.