How do you design a headless WordPress website using React.js (r) (r)
Share this on
A way to make maximum benefit from WordPress is to be totally unhindered.
The front end has to be handled separately. This is where an API comes in.
In this article, we'll go over the concept of headless CMS is, what it can do, why you may want to develop one, and the best method to configure it to integrate with WordPress.
What exactly is the Headless WordPress?
Simply put the term headless architecture implies that the CMS serves only as the storage and management of your information It doesn't even focus on the front-end of your website.
The frontend's main job however, is to display the contents. It the frontend doesn't have to care about the exact location of content is determined, as that it's able to get it.
Pros and cons of not having a head WordPress
As with all development options that exist, there are benefits as well as disadvantages when using the headless WordPress solution. It's crucial to comprehend all the benefits and drawbacks prior to making a decision.
The advantages of Headless WordPress
A few of the main advantages of using a headless WordPress implementation include the following:
- Security: By separating the the front-end and backend the headless WordPress could provide an additional layer of security by limiting access to the main WordPress database and codebase.
The pros and cons of headless WordPress
The drawbacks of WordPress that are non-headless WordPress can include:
What does it mean? The WordPress REST API?
The API supports many different data formats, including JSON making it easier to communicate via the API.
WordPress REST API is an excellent tool for web developers to build, modify or erase information, as well as create customized functionality for websites or integrate with other services. Furthermore, there are plugins made available to enhance the capabilities of the API by using additional authentication methods.
What's React?
React creates an interactive user interface that renders the component when the information changes. This is a popular library with developers seeking to develop intricate, reuseable components. efficiently manage state and easily alter the user interface at any time.
React's active developer community has developed a collection of libraries, tools, as well as resources designed to increase the performance of the library. A variety of businesses and companies have adopted React as a technology to assist in building complex fast, high-performance, and dynamic web-based applications.
What are the benefits of using React?
React has many advantages that make it an excellent alternative to create complex and interactive web-based applications.
Here are some of the most important advantages of React It is:
- Declarative syntax React employs a method to build declarative UI components. This allows you to build reusable and effective components.
- A huge community as well as an ecosystem React is home to a huge and active developer community that is a result of the creation of a wide range of software and libraries to enhance the features of React.
- Virtual DOM: React utilizes virtual DOM for changing the interface at a real-time rate. This means that whenever it changes state, it only updates the components required to alter, rather than displaying the whole page.
- Reusability React.js offers reusable components which can be used in different applications, which significantly decreases the amount of time needed to develop and working.
How Do You build a headless WordPress Website using React?
The time has come to get our hands dirty and learn how to create and then launch a bidirectional WordPress site using React.
Read on for further information.
Prerequisites
Before starting this lesson, be sure you've got:
- A good grasp of React
Step 1. Install a WordPress Website
Start by establishing your WordPress website, as it serves as the database source for React. React application. If you already have already set up a WordPress website, you can leave this part out; otherwise, you'll need to follow these steps.
Once the installation is completed after which you can access the Dev dashboard and select the New WordPress website to create a completely new WordPress website.
Enter the required information, such as and click the button to create the website button to continue.
It may take a few minutes before the website is created, however once it is up and running, you'll have access to it as well as its admin panel through selecting "Open Site" as well as WP admin options, respectively.
In order to enable to utilize the JSON API, you'll have to modify the URLs of your site.
Additionally, there are tools like Postman for testing and submit request via WordPress REST APIs.
Step 2: Setting up the React Application
Now that we have your WordPress site up and running, it is time to begin developing the frontend. As mentioned above, in this tutorial we will utilize React to act as the frontend to the software.
To begin start, you must execute the following code on your terminal, and then create a React. React application.
npm create [email protected] my-blog-app cd my-blog-app npm install
These commands will build an React application. It will then install the required dependencies.
It is also necessary to install Axios also, which is that is a JavaScript library that makes HTTP requests. Use the following command to set it up.
NPM installation Axios
To launch the server for development you can run npm run dev
in the terminal. The server should then initialize your app at http://127.0.0.1:5173.
Also, it is possible to replace the code within main.jsx and App.jsx with the following codes:
// main.jsx import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' ReactDOM.createRoot(document.getElementById('root')).render( , )
/http://www.html0.com/ App.jsx import React using'react'export the default method App() return ( )
Step 3: Fetching Posts from WordPress
It is time to pull all the information off WordPress. WordPress website.
Within the App.jsx, add the state below and include UseState
of React.
const[posts setPosts ] useState[posts setPosts, useState ([])
posts
is used to get the post's data from state. setPosts
allows you for adding more information in the article. Additionally, we've given an empty array to the state by default.
Then, add this code following the state in order to retrieve posts from the WordPress REST API
const fetchPosts = () => // Using axios to fetch the posts axios .get("http://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() , [])
The code above is running within the fetchPosts()
function on page load. Within this fetchPosts()
function, we make an request for the request to make a
call to WordPress API through Axios to search for posts. Then, we return posts to their original state that we previously declared.
Step 4: Creating the Blog Component
Within the directory that is root, you can create the directory components and within it, make two documents new: blog.jsx and blog.css.
First, add the following code to 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 ( new Date(Date.now()).toLocaleDateString("en-US", day: "numeric", month: "long", year: "numeric", ) post.title.rendered );
In the code above in the above code, we've made the card component which takes the blog's posting
property which holds the information about the blog's article. It is obtained taken from WordPress API. WordPress API.
When using in the retrieveImage()
function, we utilize Axios to find the URL of the picture which was featured and save that information to state.
Then, we included a UseEffect
hook to call to invoke on the acquireImage()
function once the component is mounted. In addition, we included a return declaration which we are rendering the content of the post, including the title excerpt, images and the post's data.
Once you have that done, add the style as described below to blog.css. blog.css file:
@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;
After that, in the App.jsx file, include the following code within your return
declaration to make the blog component:
posts.map((item) => ( )) ;
Here's how you'll need to include in your App.jsx should appear as:
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("http://my-awesome-website.local/wp-json/wp/v2/posts") .then((res) => setPosts(res.data); ); useEffect(() => fetchPosts() , []) return ( posts.map((item) => ( )) )
Save the file and refresh your browser tab. Now you should be able to view the blog post you wrote in the webpage.
Summary
Headless WordPress provides a fantastic method of creating fast-performing sites with a customizable layout. Through the use of React and using WordPress REST API WordPress REST API it's easier than ever before to design appealing and engaging websites by using WordPress for the CMS system.
Have you created or are planning to build a headless WordPress site with React? We'd love to hear from you via the comments section in the following!
This post was first seen on here