How to paginate in React.js?

Member

by shyann , in category: Javascript , a year ago

How to paginate in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , a year ago

@shyann 

In React.js, pagination can be implemented using various approaches. One of the common approaches is to maintain a state that tracks the current page and the number of items per page. Here is a step-by-step guide on how to paginate in React.js:

  1. Start by defining your component and the initial state variables for the current page and the number of items per page:
1
2
3
4
5
6
7
8
import React, { useState } from 'react';

const YourComponent = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  
  // rest of your component code
}


  1. Render your list of items using the slice method to display only the items for the current page:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const YourComponent = () => {
  // previous code

  // Assuming items is an array containing all your items
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);

  return (
    <div>
      {currentItems.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};


  1. Add pagination controls to navigate between different pages. You can use buttons or any other UI element to handle the page change:
 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
29
30
31
const YourComponent = () => {
  // previous code

  const totalPages = Math.ceil(items.length / itemsPerPage);
  
  const handlePageChange = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  
  return (
    <div>
      {currentItems.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
      
      <div>
        {Array.from({ length: totalPages }, (_, index) => index + 1).map(
          pageNumber => (
            <button
              key={pageNumber}
              onClick={() => handlePageChange(pageNumber)}
              disabled={pageNumber === currentPage}
            >
              {pageNumber}
            </button>
          )
        )}
      </div>
    </div>
  );
};


  1. You can also add additional features like a dropdown to select the number of items per page. This can be achieved by updating the itemsPerPage state variable and resetting the currentPage state when the user changes the value.


That's it! With these steps, you should be able to implement pagination in React.js. Feel free to customize the code according to your specific requirements and UI design.