Create a React App with WordPress REST API

Image is loading...

The popularity graph of PHP is getting poor nowadays. Developers are in love with the technologies such as Nodejs, Python etc. But we couldn’t neglect that WordPress, a Content Management System(CMS) platform written in PHP is still the topper by powering over 30% of the whole websites. WordPress was released on May 27 2003, and in 15 years of service, it found a huge market space in the big sea of internet.WordPress is an Open source platform and Automattic the parent company of WordPress makes money on WordPress.com by selling advertisement on free sites. If you choose to pay for their hosting plans, then you get additional premium upgrades such as the ability to hide ads, purchase domains, additional disk space, commercial themes, etc.

Now when comes to React, It is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications. It lets us compose complex UIs from small and isolated pieces of code called “components”. If we are in familiar with React, we can also build cross-platform mobile applications supporting both Android and iOS platform using React Native framework.

Here we are going to create a React app with WordPress JSON API. Common WordPress knowledge is essential to follow this tutorial. I am assuming that you have already installed WordPress on your local system and you also have some posts in it.

Now we can reach our WordPress app using,

http://localhost/wordpress-app

Where wordpress-app is the name of the WordPress project in our local system.

Note:- If you are hosting a WordPress blog on any other server, you can replace localhost with your own domain name or IP address instead.

So we can access the data of all the posts in JSON form using the below link.

http://localhost/wp-json/wp/v2/posts/

Using the post id, we can sort out the data of each post in our blog. Using the below URL, I get the JSON data of first post on my blog.

http://localhost/wp-json/wp/v2/posts/1

We can access the users, comments, media data etc. and can also perform RESTful services.

The HTTP Methods for RESTful APIs are explained below and you can refer it.

HTTP METHOD CRUD
GET Read
POST Create
PUT Update/Replace
PATCH Partial Update/Modify
DELETE Delete




CREATING AND SETTING UP OF NEW REACT PROJECT

Create-React-App is a comfortable environment for learning React and is the best way to start building a new single-page application using React. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. You’ll need to have Node >= 6 and npm >= 5.2 on your machine. To create a project, run:

npx create-react-app my-app
cd my-app
npm start

Here react-app is the name of the application we are going to create.

If everything goes well, it should be able to serve the newly created application on the development server at

http://localhost:3000/

Now we need to start working on our React app. App.js inside src directory is the root file of our application and it will be executed first.

We have to declare a state named posts as array type inside the constructor.

constructor (props){
   super(props);
   this.state = {
     posts: []
   }
 }




Then fetch the WordPress post contents using the API.

http://localhost.com/wp-json/wp/v2/posts/

This has to be loaded before the component mount. So declare a componentDidMount() and fetch the data using the API. This JSON response is stored in the posts array we declared.

componentDidMount() {
       return fetch(`http://wordpress.com/wp-json/wp/v2/posts/`)
       .then((response) => response.json())
       .then((responseJson) => {
         this.setState({
           posts: responseJson,
         })
       })
       .catch((error) => {
         console.error(error);
       })
 }

 

Now we have to render the data in posts array. I am using map() to render each post. WordPress API gives the post content as HTML. So it is easy to directly render it in react page using dangerouslySetInnerHTML.

render() {
   return (
     <div>
           {this.state.posts.map((item, index) => (
           <div>
             <div class="row">
               <div class="leftcolumn">
                 <div class="card">
                   <div className= "title">
                     <h1>{item.title.rendered}</h1>
                   </div>
                   <div className= "content" dangerouslySetInnerHTML={{ __html: item.content.rendered }} />
                 </div>
               </div>
             </div>
           </div>
           ))}
     </div>
   )
 }

I also added some CSS in App.css located inside src directory.

body {
font-family: Arial;
padding: 20px;
background: #f1f1f1;
}
.leftcolumn {

float: left;

width: 75%;
}
.card {
background-color: white;
padding: 20px;
margin-top: 20px;
}
.title {
margin-left: 50px;
margin-right: 50px;
}
.content {
margin-left: 30px;
margin-right: 30px;
margin-top: 70px;
}
h1 {
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
line-height: 1.5;
}
p {
font-family: 'Times New Roman', Times, serif;
font-size: 20px;
line-height: 1.8;
}
.row:after {
content: "";
display: table;
clear: both;
}

When you’re ready to deploy your project to production, just run

 npm run build

This will create an optimized build of your react app in the build folder.

You May Also Like

About the Author: Syamlal CM

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.