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;

Copy Text
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-

Copy Text
yarn add axios react-paginate

For npm, run this command-

Copy Text
npm install axios react-paginate

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

Import React Hooks, React Paginate, and Axios

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

Initializing React Hooks

Copy Text
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.

Copy Text
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()

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

Create a Method for Handling the Page Click

Copy Text
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.

Copy Text
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-

Copy Text
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-

Copy Text
 
.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.

Outsource Team of Dedicated React Developers

  • Result-Driven Approach
  • Integrity & Transparency
  • Profound Technical Knowledge

BOOK A 30 MIN CALL

Build Your Agile Team

Hire Skilled Developer From Us

solutions@bacancy.com

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.

How Can We Help You?