How to Use React.js to Build a Headless WordPress Site

WordPress is one of the most popular content management systems (CMS), used by 810 million websites, which accounts for 43% of the entire internet! It’s renowned for its simplicity, user-friendliness, extensive customization options, and a robust ecosystem of plugins and resources. WordPress has long been the preferred choice for those seeking to swiftly establish an online presence.

One way to harness the full potential of WordPress is by adopting a headless approach.

What Exactly Is Headless WordPress?

A headless CMS, also referred to as a headless system, serves as a backend CMS exclusively for content management. This approach allows you to seamlessly integrate content into any system or website by simply making API calls to the headless CMS. However, it does necessitate separate management of the frontend. This is where the power of APIs comes into play.

APIs, or Application Programming Interfaces, serve as bridges that facilitate data exchange between different applications. In this context, APIs serve as the conduit for transferring data from the CMS to a frontend website, offering enhanced flexibility and faster performance. In this article, we’ll explore how to leverage React.js, a widely-used JavaScript library, to build a headless WordPress site that leverages the advantages of this separation between the frontend and backend, all while maximizing the capabilities of WordPress as a CMS.

A headless WordPress website is a unique type of site that leverages WordPress exclusively as a Content Management System (CMS) while employing frontend technologies like React or Vue to handle the presentation layer.

These JavaScript libraries and frameworks take center stage in rendering the website’s content. Consequently, a headless WordPress site exhibits a clear separation between its frontend and backend, with communication facilitated through APIs.

In simpler terms, a headless architecture signifies that the CMS’s sole responsibility is to store and manage content, with no concern for the website’s frontend.

Conversely, the frontend’s primary function is to showcase content, without being constrained by where or how the content is stored; the key criterion is accessibility.

Notably, a headless WordPress site delivers enhanced performance, as frontend requests are swiftly processed by high-speed technologies like React, leaving WordPress to manage only the backend. This segregation of responsibilities enables independent scalability of frontend and backend components.

What is the WordPress REST API?

The WordPress REST API serves as an intermediary connecting the backend and frontend of a website.

  • It facilitates seamless data transmission to and from the site, granting the API control access to the site’s data.
  • The API ensures that only authorized users can interact with it, enhancing security.
  • It boasts versatile data format support, including JSON, simplifying interactions with the system.
  • For developers, the WordPress REST API is a potent tool, enabling data creation, modification, and deletion, as well as the development of custom functionality and integrations with other services.
  • Additionally, plugins are available to extend the API’s functionality, including the integration of additional authentication methods.

Here is WordPress official REST API handbook – REST API Handbook | WordPress Developer Resources

What is React.js?

React js

React.js, an open-source JavaScript framework and library developed by Facebook, stands out as a powerful tool for swiftly and efficiently constructing interactive user interfaces and web applications. This framework reduces the amount of code required compared to traditional vanilla JavaScript development.

In the realm of React, the development process centers around the creation of reusable components, akin to independent Lego building blocks. These components serve as individual pieces that, when assembled, collectively compose the entire user interface of the application. 

React primarily assumes the role of managing the view layer, reminiscent of the ‘V’ (View) in the Model-View-Controller (MVC) pattern. It excels in delivering optimal and efficient rendering execution.

Rather than treating the entire user interface as a monolithic entity, React.js encourages developers to break down complex UIs into discrete, reusable components. These components serve as the foundational elements, forming the building blocks of the complete user interface. 

In this manner, the ReactJS framework harmoniously combines the speed and efficiency of JavaScript with a more streamlined approach to manipulating the Document Object Model (DOM). This synergy results in faster web page rendering and the creation of highly dynamic, responsive web applications.

How to Make a Headless WordPress Site Using React.js? 

Now let’s make a headless WordPress site using React. But before that you need some requirements. 

Make sure you have the following items before beginning this tutorial:

  • Node.js v14 or above installed on your system
  • solid grasp of React

Step 1: Setup WordPress Site

Let’s begin by configuring the WordPress website, which will serve as the data source for the React application. You must alter your website’s permalinks to allow the JSON API.

Custom name - Headless wordpress

Click Settings, then Permalinks in the WordPress admin panel. Select the Post name choice and then click Save Changes. 

Moreover, You may also use tools like Postman to simply test and submit queries to WordPress REST APIs.

Step 2: Setting Up a React Application

Now that we’ve established our WordPress website, we can initiate work on the frontend. As previously mentioned, this tutorial will employ React for our application’s frontend.

To commence, execute the following code in your terminal to create a React application:

npm create vite@latest my-blog-app

cd my-blog-app

npm install

These commands will generate a React application and install the necessary dependencies.

Additionally, we need to incorporate Axios, a JavaScript library for making HTTP requests. Execute the subsequent command to install it:

npm install axios

To launch the development server, utilize the command npm run dev in the terminal. The server should initialize your app at https://127.0.0.1:5173.

Next, open your project in your preferred code editor and remove any superfluous files that aren’t required, such as the assets folder, index.css, and app.css.

You can also replace the content inside main.jsx and App.jsx with the following code:

// main.jsx

import React from 'react'

import ReactDOM from 'react-dom/client'

import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(

  <React.StrictMode>

    <App />

  </React.StrictMode>,

)

// App.jsx

import React from 'react'

export default function App() {

  return (

    <App />

  )

}

Step 3: Fetching Posts From WordPress

Now, let’s retrieve posts from our WordPress website.

Within App.jsx, introduce the following state and import useState from React:

const [posts, setPosts] = useState([])

useState is a built-in React hook used to introduce state to a component, with “state” referring to data or a property.

The posts state is utilized to retrieve data, and setPosts is employed to add new data to posts. We’ve initialized it with an empty array.

Subsequently, append the subsequent code after the state declaration to fetch posts from the WordPress REST API:

const fetchPosts = () => {

    // Using axios to fetch the posts

    axios

      .get("https://headless-wordpress-website.local/wp-json/wp/v2/posts")

      .then((res) => {

        // Saving the data to state

        setPosts(res.data);

      });

  }

  // Calling the function on page load

  useEffect(() => {

    fetchPosts()

  }, [])

This code executes the fetchPosts() function upon page load. Inside fetchPosts(), we send a GET request to the WordPress API using Axios to retrieve posts and then save them to the posts state declared earlier.

Step 4: Creating a Blog Component

In the root directory, generate a new folder named “components.” Inside this folder, create two new files: “blog.jsx” and “blog.css.”

First, include the following code in “blog.jsx”:

import axios from "axios";

import React, { useEffect, useState } from "react";

import "./blog.css";

export default function Blog({ post }) {

  const [featuredImage, setFeaturedImage] = useState();

  const getImage = () => {

    axios

     .get(post?._links["wp:featuredmedia"][0]?.href)

     .then((response) => {

      setFeaturedImage(response.data.source_url);

    });

  };

  useEffect(() => {

    getImage();

  }, []);

  return (

    <div class="container">

      <div class="blog-container">

        <p className="blog-date">

          {new Date(Date.now()).toLocaleDateString("en-US", {

            day: "numeric",

            month: "long",

            year: "numeric",

          })}

        </p>

        <h2 className="blog-title">{post.title.rendered}</h2>

        <p

          className="blog-excerpt"

          dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }}

        />

        <img src={featuredImage} class="mask" />

      </div>

    </div>

  );

}

In the provided code, we’ve established a card component that accepts the “post” property containing information about the blog post from the WordPress API.

Within the getImage() function, we employ Axios to fetch the URL of the featured image and store that information in state.

Additionally, we’ve included a useEffect hook to invoke the getImage() function once the component has mounted. The return statement renders the post data, including the title, excerpt, and image.

Next, add the following styles to “blog.css”:

@import url("https://fonts.googleapis.com/css?family=Poppins");

.blog-container {

  width: 400px;

  height: 322px;

  background: white;

  border-radius: 10px;

  box-shadow: 0px 20px 50px #d9dbdf;

  -webkit-transition: all 0.3s ease;

  -o-transition: all 0.3s ease;

  transition: all 0.3s ease;

}

img {

  width: 400px;

  height: 210px;

  object-fit: cover;

  overflow: hidden;

  z-index: 999;

  border-bottom-left-radius: 10px;

  border-bottom-right-radius: 10px;

}

.blog-title {

  margin: auto;

  text-align: left;

  padding-left: 22px;

  font-family: "Poppins";

  font-size: 22px;

}

.blog-date {

  text-align: justify;

  padding-left: 22px;

  padding-right: 22px;

  font-family: "Poppins";

  font-size: 12px;

  color: #c8c8c8;

  line-height: 18px;

  padding-top: 10px;

}

.blog-excerpt {

  text-align: justify;

  padding-left: 22px;

  padding-right: 22px;

  font-family: "Poppins";

  font-size: 12px;

  color: #8a8a8a;

  line-height: 18px;

  margin-bottom: 13px;

}

Lastly, in the "App.jsx" file, insert the following code inside the return statement to render the blog component:

<div>

{posts.map((item) => (

 <Blog post={item} />

))}

</div>;

Here's the final version of your "App.jsx":

import React, { useEffect, useState } from 'react'

import axios from "axios"

import Blog from './components/Blog';

export default function App() {

  const [posts, setPosts] = useState([]);

  const fetchPosts = () => {

    axios

      .get("https://my-awesome-website.local/wp-json/wp/v2/posts")

      .then((res) => {

        setPosts(res.data);

      });

  }

  useEffect(() => {

    fetchPosts()

  }, [])

  return (

    <div>

      {posts.map((item) => (

        <Blog

          post={item}

        />

      ))}

    </div>

  )

}

Save the file and refresh your browser tab. You should now see your blog posts rendered on the page.

Final Say

By combining the power of WordPress as a content management system with the flexibility of React.js for frontend development, you can create a headless WordPress site that offers both exceptional performance and a seamless user experience. The decoupled architecture allows you to leverage the strengths of each technology while enjoying the advantages of scalability, customization, and SEO optimization.

Whether you’re building a blog, an e-commerce platform, or a corporate website, the headless approach with React.js opens up a world of possibilities for creating dynamic and feature-rich websites that stand out in the digital landscape. Embrace this approach, and you’ll be well-equipped to meet the evolving demands of modern web development.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.