40 - Pagination for Long Lists of Data

Description

Create a pagination component that displays a limited number of items per page, provides navigation controls for users to move between pages, visually indicates the current page and total number of pages, and allows for jump-to-page selections for direct navigation.

Algorithm

  1. Create a React component for the pagination

  2. Define the pagination data structure (items per page, total items, current page)

  3. Use the useState hook to manage the current page and total pages

  4. Create a function to handle page navigation

  5. Render the pagination controls and item list

Classes

  • Pagination: The main pagination component

  • PaginationControl: A single pagination control component (e.g. "Previous", "Next", "Page X")

Code

Pagination.js

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

const Pagination = ({ items, itemsPerPage }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(Math.ceil(items.length / itemsPerPage));

  const handlePageNavigation = (pageNumber) => {
    setCurrentPage(pageNumber);
  };

  return (
    <div>
      <ul>
        {items.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage).map((item) => (
          <li key={item.id}>{item}</li>
        ))}
      </ul>
      <div>
        {Array.from(Array(totalPages), (_, index) => (
          <PaginationControl
            key={index}
            pageNumber={index + 1}
            currentPage={currentPage}
            onClick={() => handlePageNavigation(index + 1)}
          />
        ))}
      </div>
    </div>
  );
};

export default Pagination;

PaginationControl.js

import React from 'react';

const PaginationControl = ({ pageNumber, currentPage, onClick }) => {
  return (
    <button
      onClick={onClick}
      style={{
        backgroundColor: pageNumber === currentPage ? 'gray' : 'white',
        color: pageNumber === currentPage ? 'white' : 'black',
      }}
    >
      {pageNumber}
    </button>
  );
};

export default PaginationControl;

Explanation

The code creates a pagination component that displays a limited number of items per page, provides navigation controls for users to move between pages, visually indicates the current page and total number of pages, and allows for jump-to-page selections for direct navigation. The component uses the useState hook to manage the current page and total pages.

Possible Future Enhancements

  • Add support for dynamic item rendering

  • Add support for pagination with API data

  • Add support for custom pagination controls

  • Use a library like React Pagination for more advanced pagination functionality

Last updated