Pagination in React js is a conventional concept of distributing the data in pages with an equal number of posts. It’s main purpose is to reduces the load on the DOM Tree, and also the efficiency of our Application remains unchanged.
We can very easily create our own React Pagination with React Hooks, but using an npm package will reduce the time to make a pagination component from scratch using core JS as that had already been done by someone else.
So in this blog, we will see how to make a pagination component with the help of React Paginate NPM Package and also how to style it to our liking with its pre-defined classes.
Index
- React App
- Install npm Package
- Creating the UI part
- Using Hooks
- Getting and Displaying the data from API
- Creating the Pagination component
Let’s start ….
Creating our React App
We can very easily create our React App with the following command.
create-react-app react-pagination
For this to work, you should have npm and node installed in your system and then navigate using the cd command to the folder where you want to create your react app.
We will be using bootstrap for this project with its CDN link for CSS and JS Bundle. You can use the npm package React-Bootstrap also.
Installing our Package
The package we will be using is React-Pacginate which can be installed by typing the following in our command prompt under the name of our Application or in Powershell
npm install react-paginate
And writing the below line in our App.js file
import ReactPaginate from ‘react-paginate’;
Creating the table for our data
We will be using an API for getting our large sum of data. Now we will create our table for displaying this data.
import React, { useState, useEffect } from "react";
const Pagination = () => {
return (
<>
<div className="container-fluid">
<div className="row">
<table>
<thead>
<tr className="border-2 border-dark text-center my-2">
<th className="col-1 border-2 border-dark fs-4 text-capitalize">
S No.
</th>
<th className="col-3 border-2 border-dark fs-4 text-capitalize">
Name
</th>
<th className="col-2 border-2 border-dark fs-4 text-capitalize">
Email
</th>
<th className="col-6 border-2 border-dark fs-4 text-capitalize">
Comment
</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</>
);
};
export default Pagination;
Now we have our basic structure. Let us move towards API dealing.
The API contains 500 sets of data in the given form
body: “laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium“
email: “Eliseo@gardner.biz“
id: 1
name: “id labore ex et quam laborum“
postId: 1
Applying Hooks
For getting the data from our API, we will be using the async-await concept with useEffect Hook and useState Hooks
useEffect(() => {
const fetchApi = async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/comments");
const dataJ = await data.json();
console.log(dataJ);
};
fetchApi();
}, []);
Now we will be defining some states using the useState Hook.
const [post, setPost] = useState([]);
const [number, setNumber] = useState(1); // No of pages
const postPerPage = 10;
The first useState is used for the data of the API that is initially defined as an empty array.
The Second useState is used for page numbers. Initially, there will be one as we are working on it.
The third constant is used for the number of table data per page, I have kept it at 10 but you can change it.
Displaying the Data
We will be using the map method and the post-state as it contains the data from the API.
import React, { useState, useEffect } from "react";
const Pagination = () => {
const [post, setPost] = useState([]);
const [number, setNumber] = useState(1); // No of pages
const postPerPage = 10;
useEffect(() => {
const fetchApi = async () => {
const data = await fetch("https://jsonplaceholder.typicode.com/comments");
const dataJ = await data.json();
console.log(dataJ);
setPost(dataJ);
};
fetchApi();
}, []);
return (
<>
<div className="container-fluid">
<div className="row">
<table>
<thead>
<tr className="border-2 border-dark text-center my-2">
<th className="col-1 border-2 border-dark fs-4 text-capitalize">
S No.
</th>
<th className="col-3 border-2 border-dark fs-4 text-capitalize">
Name
</th>
<th className="col-2 border-2 border-dark fs-4 text-capitalize">
Email
</th>
<th className="col-6 border-2 border-dark fs-4 text-capitalize">
Comment
</th>
</tr>
</thead>
<tbody>
{post.map((Val) => {
return (
<>
<tr
className="border-2 border-dark text-center"
key={Val.id}
>
<td className="border-2 border-dark text-capitalize">
{Val.id}
</td>
<td className="border-2 border-dark text-capitalize">
{Val.name}
</td>
<td className="border-2 border-dark text-capitalize">
{Val.email}
</td>
<td className="border-2 border-dark text-capitalize">
{Val.body}
</td>
</tr>
</>
);
})}
</tbody>
</table>
</div>
</div>
</>
);
};
export default Pagination;
We will be seeing a table containing an insane amount of values (500).
Creating the Pagination
For this, we need some predefined values which we will use for making the pagination component.
const lastPost = number * postPerPage;
const firstPost = lastPost - postPerPage;
const currentPost = post.slice(firstPost, lastPost);
Now, let’s change the post with currentPost as it will show us only the number of posts that we wanted on a single page.
We have a component and some props that we can use from the package to define and style the Pagination Component
<ReactPaginate
previousLabel={"Previous"}
nextLabel={"Next"}
pageCount={PageCount}
onPageChange={ChangePage}
containerClassName={"paginationBttns"}
activeClassName={"paginationActive"}
marginPagesDisplayed={4}
pageRangeDisplayed={4}
></ReactPaginate>
ReactPaginate is the component that will give us our pagination and the rest are the props that are used for defining and styling them.
.paginationBttns {
width: 100%;
display: flex;
list-style: none;
justify-content: center;
margin: 2% 0;
}
.paginationBttns a {
border: 2px solid black;
padding: 5px 15px;
border-radius: 50px;
margin: 0 5px;
}
The above is an example of how to style it. Read the documentation for more info and can even see a demo code for a better understanding.
For getting page numbers dynamically, add the following piece of code
const PageCount = Math.ceil(post.length / postPerPage);
Our Pagination will look something like this
The method is used to round off any decimal values as we cant have our page numbers in decimals. You can check the page numbers by
console.log(pageCount)
We will set an onPageChange handler to render the below function when the button is clicked.
const ChangePage = ({ selected }) => {
setNumber(selected);
};
Selected is also one of the props of React-Paginate which will help us in displaying data of the corresponding page number.
Now we have every button in working condition, and we can render any page from its page number.
Conclusion
Pagination is a concept that goes way back and helps us in dividing data into several pages which contain a fixed number of posts because of which there will be no difficulty with the efficiency and loading speed of our App.
But, this package has one major problem: it takes page 1 as zero as its index number. Thus there will be no content on page 1 and the content will start displaying itself from page 2.
For the complete source code, visit my Github page, and for a demo visit my code sandbox.
I think the admin of this site is really working hard for his site, for the reason that here every material is quality based stuff.|