Building a Custom Pagination Component in React

By Maulik Paghdal

12 Dec, 2024

Building a Custom Pagination Component in React

Introduction

Pagination is an essential feature in web applications for displaying data in manageable chunks. While many libraries provide pre-built solutions, creating your custom pagination component in React gives you flexibility and control over the design and functionality.

In this blog, we’ll walk through building a reusable and customizable pagination component from scratch.

Setting Up the Project

First, ensure you have a React application set up. You can use create-react-app or any other boilerplate of your choice.

npx create-react-app react-pagination
cd react-pagination
npm start

Understanding the Pagination Logic

Pagination involves splitting a dataset into pages. To achieve this, we need the following:

  1. Total number of items.
  2. Items per page.
  3. Current page.
  4. Logic to calculate the range of items displayed.

Creating the Pagination Component

Step 1: Define the Pagination Component

We’ll create a functional component that accepts props for totalItems, itemsPerPage, currentPage, and a callback function to handle page changes.

import React from 'react';

function Pagination({ totalItems, itemsPerPage, currentPage, onPageChange }) {
  const totalPages = Math.ceil(totalItems / itemsPerPage);
  const pages = Array.from({ length: totalPages }, (_, i) => i + 1);

  return (
    <div className="pagination">
      <button 
        onClick={() => onPageChange(currentPage - 1)} 
        disabled={currentPage === 1}
      >
        Previous
      </button>
      {pages.map((page) => (
        <button
          key={page}
          onClick={() => onPageChange(page)}
          className={currentPage === page ? 'active' : ''}
        >
          {page}
        </button>
      ))}
      <button 
        onClick={() => onPageChange(currentPage + 1)} 
        disabled={currentPage === totalPages}
      >
        Next
      </button>
    </div>
  );
}

export default Pagination;

Step 2: Styling the Pagination Component

Use CSS to style the pagination component for better user experience.

.pagination {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background: #fff;
  cursor: pointer;
}

.pagination button.active {
  background: #007bff;
  color: #fff;
  border-color: #007bff;
}

.pagination button:disabled {
  background: #e9ecef;
  cursor: not-allowed;
}

Step 3: Integrating the Component

Use the Pagination component in a parent component to manage paginated data.

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

function App() {
  const items = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5;

  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);

  return (
    <div className="App">
      <ul>
        {currentItems.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      <Pagination
        totalItems={items.length}
        itemsPerPage={itemsPerPage}
        currentPage={currentPage}
        onPageChange={(page) => setCurrentPage(page)}
      />
    </div>
  );
}

export default App;

Advanced Customizations

To enhance your pagination component, consider adding:

  1. Ellipsis for long page ranges.
  2. Dropdown to select items per page.
  3. Accessibility features (ARIA attributes).

Conclusion

Building a custom pagination component in React not only improves your understanding of React concepts but also allows you to tailor the design and functionality to your application’s needs. With the above approach, you can manage large datasets and provide a seamless user experience.

Try creating your own pagination component today!

Topics Covered