Table of Contents

Introduction

We often end up having a web application with a large number of data to be displayed. And at that time, Pagination comes to the rescue for managing such a vast dataset. In this blogpost, we will build a small application to implement ReactJS pagination using React Hooks and a package named React Paginate. Without further ado, let’s start coding!

Here is the source code for React pagination example -> Github Repository. You can clone the repository and play around with the code. Let’s have a look at how to make pagination in ReactJS.

How to Implement Pagination Using React Hooks and React Paginate?

Create and Navigate to your React pagination project;

npx create-react-app react-pagination
cd react-pagination

Here’s How to Install Axios and React Paginate

Based on your package manager, install Axios and React Paginate.

For yarn, run this command-

yarn add axios react-paginate

For npm, run this command-

npm install axios react-paginate

Now, open App.js and make the necessary changes.

Import React Hooks, React Paginate, and Axios

import React, { useState, useEffect } from 'react'
import axios from 'axios'
import ReactPaginate from 'react-paginate';

Initializing React Hooks

const [postsPerPage] = useState(5);
const [offset, setOffset] = useState(1);
const [posts, setAllPosts] = useState([]);
const [pageCount, setPageCount] = useState(0)

Fetching Data Using Axios

We will use a dummy API -> https://jsonplaceholder.typicode.com/posts to fetch the data and display it. getAllposts() will be an async function that will return a response containing 100 posts. In getPostData(), we will manipulate data according to the HTML structure that needs to be displayed.

const getPostData = (data) => {
   return (
     data.map(post => <div className="container" key={post.id}>
       

User ID: {post.id}
       

Title: {post.title}
     </div>)
   )
 }
const getAllPosts = async () => {
   const res = await   axios.get(`https://jsonplaceholder.typicode.com/posts`)
   const data = res.data;
   const slice = data.slice(offset - 1 , offset - 1 + postsPerPage)
 
   // For displaying Data
   const postData = getPostData(slice)
 
   // Using Hooks to set value
   setAllPosts(postData)
   setPageCount(Math.ceil(data.length / postsPerPage))
 }
 
 const handlePageClick = (e) => {
   const selectedPage = e.selected;
   setOffset(selectedPage + 1)
 };
 

Here we will fetch data using Axios and then store the response in the variable named data. The motive behind the JavaScript function – slice, is to slice our data, i.e., 100array.slice(0, 0+5)). Further, we will loop the data using a map function, return the HTML structure and store it in the variable named postData. Then, update the state with postData using React hook setAllPosts. This was related to updating our data. Now, for updating the pageCount we will use (Math.ceil(data.length / postsPerPage)) and further store it using setPageCount hook.

Quick Read: A Comprehensive Guideline to UseState In React Hooks

Call getAllPosts() from React hooks – useEffect()

useEffect(() => {
   getAllPosts()
 }, [offset])

Create a Method for Handling the Page Click

const handlePageClick = (event) => {
   const selectedPage = event.selected;
   setOffset(selectedPage + 1)
 };

Now you just need to return your posts and implement the ReactPaginate tag using some of its props. We will call handlePageClick() using onPageChange props, so whenever we click on next or previous, the method handlePageClick() will be called.

return (
   <div className="main-app">
    
     { /* Display all the posts  */ }
     { posts }
 
     { /* Using React Paginate */ }
     <ReactPaginate
       previousLabel={"previous" }
       nextLabel={ "next" }
       breakLabel={ "..." }
       breakClassName={ "break-me" }
       pageCount={ pageCount }
       onPageChange={ handlePageClick }
       containerClassName={ "pagination" }
       subContainerClassName={ "pages pagination" }
       activeClassName={ "active" } />
   </div>
 );

After implementing the above code snippets, your App.js would look something like this-

import React, { useState, useEffect } from 'react'
import axios from 'axios'
import ReactPaginate from 'react-paginate';
import './App.css'
 
function App() {
 const [postsPerPage] = useState(5);
 const [offset, setOffset] = useState(1);
 const [posts, setAllPosts] = useState([]);
 const [pageCount, setPageCount] = useState(0)
 
 const getPostData = (data) => {
   return (
     data.map(post => <div className="container" key={post.id}>
       <p>User ID: {post.id}</p>
       <p>Title: {post.title}</p>
     </div>)
   )
 
 }
 
 const getAllPosts = async () => {
   const res = await axios.get(`https://jsonplaceholder.typicode.com/posts`)
   const data = res.data;
   const slice = data.slice(offset - 1 , offset - 1 + postsPerPage)
 
   // For displaying Data
   const postData = getPostData(slice)
 
   // Using Hooks to set value
   setAllPosts(postData)
   setPageCount(Math.ceil(data.length / postsPerPage))
 }
 
 const handlePageClick = (event) => {
   const selectedPage = event.selected;
   setOffset(selectedPage + 1)
 };
 
 useEffect(() => {
   getAllPosts()
 }, [offset])
 
 return (
   <div className="main-app">
    
     {/* Display all the posts */}
     {posts}
 
     {/* Using React Paginate */}
     <ReactPaginate
       previousLabel={"previous"}
       nextLabel={"next"}
       breakLabel={"..."}
       breakClassName={"break-me"}
       pageCount={pageCount}
       onPageChange={handlePageClick}
       containerClassName={"pagination"}
       subContainerClassName={"pages pagination"}
       activeClassName={"active"} />
   </div>
 );
}
 
export default App;

In case you want CSS code for App.css; it’s here-

 
.main-app {
 margin: 2% 10%;
 border: 1px ridge #464141;
 padding: 5%;
 font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
 font-size: 20px;
 color: #464141;
}
 
.container {
 border-bottom: #fff 2px ridge;
}
 
.pagination {
 margin-top: 45px;
 margin-left: -40px;
 display: flex;
 list-style: none;
 outline: none;
}
 
.pagination>.active>a {
 background-color: #47ccde;
 color: #fff;
}
 
.pagination>li>a {
 border: 1px solid #47ccde;
 padding: 5px 10px;
 outline: none;
 cursor: pointer;
}
 
.pagination>li>a, .pagination>li>span {
 color: #47ccde;
 background-color: azure;
}

Conclusion

I hope this comprehensive tutorial of ReactJS pagination using React hooks and React paginate has helped you the way you’ve expected. If you are looking for a helping hand to implement pagination using React hooks and React paginate then Hire React developer to leverage the expertise.

Vivek Patel

Vivek Patel

Full Stack Developer at Bacancy

Engineering director and React expert leading innovation through code and collaboration.

MORE POSTS BY THE AUTHOR
SUBSCRIBE NEWSLETTER

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.