Fetching Data from WordPress REST API
First, we need to fetch data from the WordPress REST API. The API provides pagination through the _page and _per_page query parameters. Here is a basic example of how to fetch paginated posts.
API Call Example
const fetchPosts = async (page, perPage) => {
const response = await fetch(`https://your-wordpress-site.com/wp-json/wp/v2/posts?page=${page}&per_page=${perPage}`);
const data = await response.json();
return data;
};
Setting Up React Component
Next, we will create a React component that handles fetching and displaying posts with pagination.
React Component Example
import React, { useState, useEffect } from 'react';
const Posts = () => {
const [posts, setPosts] = useState([]);
const [page, setPage] = useState(1);
const [totalPages, setTotalPages] = useState(1);
const perPage = 5;
useEffect(() => {
const fetchData = async () => {
const response = await fetch(`https://your-wordpress-site.com/wp-json/wp/v2/posts?page=${page}&per_page=${perPage}`);
const data = await response.json();
const totalPages = response.headers.get('X-WP-TotalPages');
setPosts(data);
setTotalPages(totalPages);
};
fetchData();
}, [page]);
const handleNextPage = () => {
if (page < totalPages) {
setPage(page + 1);
}
};
const handlePreviousPage = () => {
if (page > 1) {
setPage(page - 1);
}
};
return (
<div>
<h1>WordPress Posts</h1>
<ul>
{posts.map(post => (
<li key={post.id}>
<h2>{post.title.rendered}</h2>
<div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
</li>
))}
</ul>
<div>
<button onClick={handlePreviousPage} disabled={page === 1}>
Previous
</button>
<span> Page {page} of {totalPages} </span>
<button onClick={handleNextPage} disabled={page === totalPages}>
Next
</button>
</div>
</div>
);
};
export default Posts;
Explanation
- State Management: We use the
useStatehook to manage the posts, current page, and total pages. - Fetching Data: The
useEffecthook fetches data whenever thepagestate changes. - Handling Pagination: We define
handleNextPageandhandlePreviousPagefunctions to update thepagestate and navigate through pages. - Rendering Posts: We map through the
postsarray and display the post title and excerpt.
Step 3: Integrate Component into Your App
Finally, integrate the Posts component into your main React application.
App Component Example
import React from 'react';
import Posts from './Posts';
function App() {
return (
<div className="App">
<Posts />
</div>
);
}
export default App;