In this guide, you will learn how to create a simple app using React and the WordPress REST API. By the end, you will have a basic app that fetches posts from a WordPress site and displays them in a React frontend.
Final Output
Here’s what the app will look like:
- A list of posts fetched from the WordPress REST API.
- A single post view when you click on a post title.
Step 1: Set Up Your React Project
Start by creating a new React project:
npm install -g create-react-app
create-react-app wp-rest
Clean Up the Project
Navigate to the project folder and remove all files in the src/
directory:
cd wp-rest
rm -f src/*
Create Essential Files
- Add a new file named
index.js
in thesrc/
folder. - Add a new file named
index.css
in thesrc/
folder.
Import React in index.js
Add the following lines at the top of index.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
Step 2: Create a Static Post List
In index.js
, add a simple React component to display static posts:
class App extends React.Component {
render() {
return (
<div className="posts">
<h1>Latest Posts</h1>
<ul>
<li>
<h2>How to Wear Boots with Jeans</h2>
<span>2 Feb 2018</span>
</li>
<li>
<h2>How to Lose Weight Through Clean Eating</h2>
<span>2 Feb 2018</span>
</li>
<li>
<h2>How to Delete a Table in Word</h2>
<span>2 Feb 2018</span>
</li>
</ul>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Run the app with:
npm start
Visit http://localhost:3000/
to see a static list of posts.
Step 3: Fetch Posts from the WordPress REST API
Now, replace the static posts with data fetched from the WordPress REST API.
Add State to the Component
Update the App
component to include a state for storing posts:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
singlePost: null,
isLoading: true,
error: null,
};
}
componentDidMount() {
fetch('http://your-wordpress-site.com/wp-json/wp/v2/posts')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => this.setState({ posts: data, isLoading: false }))
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { posts, singlePost, isLoading, error } = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
return (
<div className="posts">
<h1>Latest Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<h2 onClick={() => this.setState({ singlePost: post })}>{post.title.rendered}</h2>
<span>{new Date(post.date).toLocaleDateString()}</span>
</li>
))}
</ul>
</div>
);
}
}
Step 4: Add Single Post View
Add a single post view to display the content when a post title is clicked:
render() {
const { posts, singlePost, isLoading, error } = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
if (error) {
return <p>Error: {error.message}</p>;
}
if (singlePost) {
return (
<div className="single-post">
<button onClick={() => this.setState({ singlePost: null })}>
Back to Posts
</button>
<h1>{singlePost.title.rendered}</h1>
<div dangerouslySetInnerHTML={{ __html: singlePost.content.rendered }} />
</div>
);
}
return (
<div className="posts">
<h1>Latest Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<h2 onClick={() => this.setState({ singlePost: post })}>{post.title.rendered}</h2>
<span>{new Date(post.date).toLocaleDateString()}</span>
</li>
))}
</ul>
</div>
);
}
Step 5: Add CSS Styling
Create a basic style for your app in index.css
:
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.posts, .single-post {
width: 80%;
margin: 0 auto;
}
h1 {
color: #333;
}
ul {
list-style: none;
padding: 0;
}
li {
margin: 10px 0;
cursor: pointer;
}
button {
background-color: #0073aa;
color: white;
border: none;
padding: 10px;
cursor: pointer;
}
button:hover {
background-color: #005a8c;
}
Conclusion
You’ve built a simple React app that uses the WordPress REST API to fetch and display posts. Here’s a quick summary of what you learned:
- Setting up a React app.
- Fetching data from the WordPress REST API.
- Using React’s state and lifecycle methods.
- Adding single post view functionality.
- Basic styling.
Stay tuned for the next tutorial where we’ll cover user authentication, creating posts, and code splitting! 🚀
Thank you for reading!
Leave a Reply