Back to all posts

Using WordPress REST API with Pagination in React


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 useState hook to manage the posts, current page, and total pages.
  • Fetching Data: The useEffect hook fetches data whenever the page state changes.
  • Handling Pagination: We define handleNextPage and handlePreviousPage functions to update the page state and navigate through pages.
  • Rendering Posts: We map through the posts array 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;