How to show pagination in ReactJS?


The pagination allows users to show content on different pages. For example, we have thousands of data and want to show that to users on a single webpage. It will look worse if we show thousands of data on a single page, as users must scroll through all data to reach the last data.

So, to solve the issue, pagination comes into the picture. We can show a particular number of data on a single page and create a total number of pages according to the total data available. Gmail is the best example of pagination, it shows 50 emails per page, and users can change the page to see other emails.

Use the react-paginate NPM Package

The react-paginate is an NPM package allowing to add the pagination in the react application. We need to import the ReactPaginate component from the package and use it in the application. Also, we need to pass some values as a prop. For example, pageCount shows the total number of pages on the screen.

Users can execute the below command in the project directory to install the react-paginate NPM package in the react application.

npm i react-paginate

Syntax

Users can follow the syntax below to use the ReactPaginate component to show pagination in the React application.

<ReactPaginate
   pageCount = {Math.ceil(
      total data / ItemsPerPage
   )}
   onPageChange = {Invoke_func}
/>

In the above syntax, users can observe that we calculate total pages based on the total data and items per page. Also, we can execute any function whenever users change the page.

Example

In the example below, we have defined the state object in the class component. In the state object, we have defined and initialized the required variable. We have added the 28 items to the Data variable.

After that, we added some props to the ReactPaginate component. Whenever the user clicks on any page, we call the handlePageclick() function. In the function, we get the selected page, slice the data from the ‘allData’ state variable accordingly and store the respected data in the ‘currentData’ state variable. Also, we show the current data on the web page.

Also, we have added some CSS in the App.css file using Bootstrap. In the output, users can observe that whenever they change the page, it changes the data accordingly.

Filename – App.js

import React, { Component } from "react";
import ReactPaginate from "react-paginate";
import "./App.css";

export default class App extends Component {
   constructor(props) {
      super(props);
      
      // defining the state for the component
      this.state = {
         offset: 0,
         
         // defining the data that will be displayed
         allData: [
            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
            21, 22, 23, 24, 25, 26, 27, 28,
         ],
         
         // data for selected page
         currentData: [1, 2, 3, 4, 5],
         
         // total pages
         ItemsPerPage: 5,
         currentPage: 0,
      };
      this.handlePageClick = this.handlePageClick.bind(this);
   }
   getData = () => {
      // slice the data according to requirements
      const data = this.state.allData;
      const slice = data.slice(
         this.state.offset,
         this.state.offset + this.state.ItemsPerPage
      );
      // update the data
      this.setState({
         currentData: slice,
      });
   };

   handlePageClick = (e) => {
      // on page change, update the state
      const currentPage = e.selected;
      const offset = currentPage * this.state.ItemsPerPage;

      this.setState(
         {
            currentPage: currentPage,
            offset: offset,
         },
         () => {
            // update the current data
            this.getData();
         }
      );
   };

   render() {
      return (
         <div>
            {/* show data in the products form */}
            {this.state.currentData.map((item, index) => {
               return <h3 key = {index}> Product {item} </h3>;
            })}
            <ReactPaginate
               containerClassName = {"pagination"}
               pageCount = {Math.ceil(
                  this.state.allData.length / this.state.ItemsPerPage
               )}
               marginPagesDisplayed = {2}
               pageRangeDisplayed = {5}
               onPageChange = {this.handlePageClick}
               activeClassName = {"active"}
            />
         </div>
      );
   }
}

Filename – App.css

@import "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css";

#container {
   margin:10px;
}

.items {
   margin-bottom:10px;
}

.pagination {
   list-style: none;
   outline: none;
   margin: 15px auto;
   display: flex;
}

.pagination > li > a {
   border: 1px solid blue;
   padding: 5px 10px;
   outline: none;
   text-decoration: none;
   cursor: pointer;
}

Output

Use the Material Ui’s Paginate component

The Material UI library contains the Pagination component, which we can directly import into the react application to use it.

Execute the below command in the terminal to install the Material UI.

npm install @mui/material @emotion/react @emotion/styled

Syntax

Users should follow the syntax below to use the Pagination component of Material UI.

<Pagination count = {5} shape = "rounded" />

In the above syntax, we have passed the count representing the total number of pages and the shape of page items as a prop.

Example

In the example below, we have imported the Pagination component from Material UI and added the different variants of it by passing multiple props.

In the output, users can observe that we have given a rounded shape to the page components. We have added the color and outline in the second Pagination component. Furthermore, we have shown the arrow buttons in the third Pagination component and disabled the pages in the final Pagination component.

import React from "react.js";
import Pagination from "@mui/material/Pagination";

const App = () => {
   return (
      <div>
         <h2>
            Using the <i> Pagination component of </i> Material UI library to create
            paginations in ReactJS.{" "}
         </h2>

         <Pagination count = {5} shape = "rounded" />
         <br></br>
         <Pagination count = {7} variant = "outlined" color = "primary" />
         <br></br>
         <Pagination count = {6} showFirstButton showLastButton />
         <br></br>
         <Pagination count = {13} variant = "outlined" disabled />
      </div>
   );
};

Output

We learned two approaches to creating pagination in ReactJS. The first approach uses the react-paginate NPM package, and the second uses the Material UI library. Also, users can create a custom Pagination component from scratch in ReactJS if they have a vast knowledge of handling pagination functionalities.

Updated on: 05-Apr-2023

389 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements