Categories: How toReact JS

How to Make Custom Pagination In React js with Hooks

We often find ourselves in a situation where we have to deal with large sums of data in our Application for user experience. If we render the data, in the same way, using the map function, the DOM Tree and the efficiency of our app will suffer the consequences like effects on speed and loading time, etc.

There are four solutions to this problem, and pagination is one of them. It divides the content into pages decreasing the pressure on the DOM Tree and keeping our efficiency unharmed.

Here, we’ll discuss a way of creating custom pagination in React js with the help of Hooks.

You can also see how to make a pagination component using an NPM package “React-Paginate”

Index

Let’s begin….

Creating our React App

Creating a React App is very easy, just type the following command in the command prompt

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.

Bootstrap will be used from their CDN links for this project, you can use it any other way too.

Creating the table for our data

An API for getting our large sum of data. Now we will create our table for displaying this data.

Now we have our basic structure. Let us move towards API dealing.

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;

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();
  }, []);

using the useState hook, we will define some states like

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 (
   
 
export default Pagination;

 <>
      <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>
    </>
  );
};

We will be seeing a table containing an insane amount of values (500) like this –

Table with 500 values

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.

Now for the dynamic page numbers, we have to use the for loop

const pageNumber = [];
 
  for (let i = 1; i <= Math.ceil(post.length / postPerPage); i++) {
    pageNumber.push(i);
  }

The ceil 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(pageNumber)
 <div className="my-3 text-center">
            <button
              className="px-3 py-1 m-1 text-center btn-primary"
            >
              Previous
            </button>
 
            {pageNumber.map((Elem) => {
              return (
                <>
                  <button
                    className="px-3 py-1 m-1 text-center btn-outline-dark"
                    >
                    {Elem}
                  </button>
                </>
              );
            })}
            <button
              className="px-3 py-1 m-1 text-center btn-primary"
            >
              Next
            </button>
          </div>

From the above code, we now have our page numbers and the next and previous buttons

Pagination Component

We will set an onClick handler to render a function when the button is clicked.

 <div className="my-3 text-center">
            <button
              className="px-3 py-1 m-1 text-center btn-primary"
              onClick={() => setNumber(number - 1)}
            >
              Previous
            </button>
 
            {pageNumber.map((Elem) => {
              return (
                <>
                  <button
                    className="px-3 py-1 m-1 text-center btn-outline-dark"
                    onClick={() => ChangePage(Elem)}
                  >
                    {Elem}
                  </button>
                </>
              );
            })}
            <button
              className="px-3 py-1 m-1 text-center btn-primary"
              onClick={() => setNumber(number + 1)}
            >
              Next
            </button>
          </div>

  const ChangePage = (pageNumber) => {
    setNumber(pageNumber);
  };

Now we have every button in working condition, and we can render any page from its page number

Conclusion

Pagination gives us a way to render large pieces of data by dividing them into several pages of equal posts. The best example to understand pagination is google.

Google distributes the websites, posts, and many other things into pages whose number is not fixed either, but the number of posts is fixed and will always be.

For the complete source code, visit my Github page, and for a demo visit my code sandbox.

Ateev Duggal

I am Ateev Duggal, a front-end web developer, and a blogger. I write blogs mainly on React JS and have an experience of over 1.5 years of freelancing. I have worked on both static and dynamic projects again using React JS like a table to show clients data which was fetched using API, a review slider, pagination component, etc, and many websites like Parent, landing pages for Ataota, and many more. Some of my blogs have been published on freecodecamp, dev.to, Medium, geeks for geeks, and many other blogging platforms and developer's communities. My Primary skills not only include React JS but HTML5, CSS3, JS, Jquery, Git, and Bootstrap also. You can visit my GitHub Profile and LinkedIn profile for more information about me or you can visit my Website at tekolio.com

Share
Published by
Ateev Duggal

Recent Posts

What is Inheritance in Java and why is it important?

Inheritance in Java is a mechanism of creating a new class or interface from an…

2 months ago

Understanding the Fundamentals of OOPS in Java

In this blog, we will not only understand the concepts of OOPS in Java in…

3 months ago

OOPS Concepts 101: What Are the Key Concepts You Need to Know?

Object-Oriented Programming System (OOPS) is a programming paradigm built around the concept of objects —…

3 months ago

What is abstraction in Java and how to achieve it?

Abstraction in Java is one of the four pillars of OOPs which is used to…

1 year ago

How to Detect a Click Outside of a React Component using Hooks?

In this blog, we will learn How to Detect a Click Outside of a React…

2 years ago

How to Implement Infinite Scrolling in React by Making a Custom Hook

learn How to Use Hooks to Create Infinite Scrolling in React by making a custom…

2 years ago