How can we create a Pagination in react

Creating pagination in a React application involves managing the current page state and rendering the appropriate page content based on user interactions.

import React, { useState } from 'react';


const Pagination = ({ totalItems, itemsPerPage, onPageChange }) => {
  const [currentPage, setCurrentPage] = useState(1);


  // Calculate the total number of pages
  const totalPages = Math.ceil(totalItems / itemsPerPage);


  // Handle page change
  const handlePageChange = (page) => {
    setCurrentPage(page);
    onPageChange(page);
  };


  // Generate page numbers
  const renderPageNumbers = () => {
    const pageNumbers = [];
    for (let i = 1; i <= totalPages; i++) {
      pageNumbers.push(
        <li
          key={i}
          onClick={() => handlePageChange(i)}
          className={currentPage === i ? 'active' : ''}
        >
          {i}
        </li>
      );
    }
    return pageNumbers;
  };


  return (
    <div className="pagination">
      <ul className="page-numbers">
        {renderPageNumbers()}
      </ul>
    </div>
  );
};


export default Pagination;

And in this How we use Pagination in the react

import React, { useState } from 'react';
import Pagination from './Pagination';


const App = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5; // Adjust as needed


  // Function to fetch data for the current page
  const fetchDataForPage = (page) => {
    // Implement logic to fetch data for the given page
    console.log(`Fetching data for page ${page}`);
  };


  // Handle page change
  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchDataForPage(page);
  };


  return (
    <div>
      {/* Render your content for the current page */}
      <div>
        <h1>Page {currentPage}</h1>
        {/* Render your content here */}
      </div>
      
      {/* Render pagination component */}
      <Pagination
        totalItems={100} // Provide total number of items
        itemsPerPage={itemsPerPage}
        onPageChange={handlePageChange}
      />
    </div>
  );
};


export default App;

  • The Pagination component renders a list of page numbers based on the total number of items and items per page.
  • It uses state to track the current page.
  • The handlePageChange function updates the current page state and fetches data for the new page.
  • we can adjust the itemsPerPage and totalItems props according to our application’s requirements.
  • we need to implement logic insidefetchDataForPage to fetch data for the given page.

Leave a comment

Your email address will not be published. Required fields are marked *