How to Make Pagination in React JS

Created by Ahmad Negm

2023-04-22

thumbnails
thumbnails
thumbnails

How to Make Pagination in React JS

Pagination is a way to break up large amounts of data into smaller, more manageable pages. It is a common feature of many websites and web applications.

In React JS, pagination can be implemented using the

1Pagination
component from the
1react-paginate
library. The
1Pagination
component takes a number of props, including:

  • 1totalItems

    : The total number of items in the dataset.

  • 1perPage

    : The number of items to display per page.

  • 1currentPage

    : The current page number.

  • 1onPageChange

    : A function that is called when the page number changes.

Here is an example of how to use the

1Pagination
component:

1JavaScript
1import React, { useState } from "react";
2import Pagination from "react-paginate";
3
4const App = () => {
5  const [items, setItems] = useState([
6    { id: 1, name: "Item 1" },
7    { id: 2, name: "Item 2" },
8    { id: 3, name: "Item 3" },
9    { id: 4, name: "Item 4" },
10    { id: 5, name: "Item 5" },
11  ]);
12
13  const [currentPage, setCurrentPage] = useState(1);
14
15  const handlePageChange = (page) => {
16    setCurrentPage(page);
17  };
18
19  return (
20    <div>
21      <Pagination
22        totalItems={items.length}
23        perPage={10}
24        currentPage={currentPage}
25        onPageChange={handlePageChange}
26      />
27      <ul>
28        {items.slice((currentPage - 1) * perPage, currentPage * perPage).map((item) => (
29          <li key={item.id}>{item.name}</li>
30        ))}
31      </ul>
32    </div>
33  );
34};
35
36export default App;

This code will create a pagination component with 10 items per page. The current page number is displayed in the pagination component, and the user can change the page number by clicking on the links. When the user changes the page number, the list of items is updated to display the items on the new page.