React Paginate

Pagination in React is a method for dividing large sets of data or content into smaller, more manageable pages, enhancing both performance and user experience.

With pagination, users can navigate through different pages of data instead of loading everything at once.

Why Use Pagination in React?

  1. Improved Performance: Loading large data sets at once can slow down an application. Pagination loads data in chunks, reducing page load time.
  2. Enhanced User Experience: Users can focus on smaller, relevant sections of content without being overwhelmed.
  3. Better Data Management: Pagination allows easy management and organization of content, especially in data-heavy applications.

Implementing Pagination in React

Pagination in React can be implemented either by custom code or by using libraries. Here, we’ll explore both approaches.

Custom Pagination in React

Creating custom pagination involves managing page numbers, keeping track of the current page, and setting how many items to display per page.

  1. Data Array: An array containing the data to be paginated.
  2. State Variables:
    • currentPage: Holds the current page number.
    • itemsPerPage: Defines how many items will be shown per page.
  3. Functions:
    • handleNextPage and handlePrevPage: Functions to handle navigation between pages.
    • handlePageChange: Sets the current page based on the user’s selection.

Basic Example of Custom Pagination

import React, { useState } from 'react';

function PaginationExample({ data }) {
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;

// Calculate total pages
const totalPages = Math.ceil(data.length / itemsPerPage);

// Get current items
const startIndex = (currentPage - 1) * itemsPerPage;
const currentItems = data.slice(startIndex, startIndex + itemsPerPage);

const handleNextPage = () => {
if (currentPage < totalPages) {
setCurrentPage((prevPage) => prevPage + 1);
}
};

const handlePrevPage = () => {
if (currentPage > 1) {
setCurrentPage((prevPage) => prevPage - 1);
}
};

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

return (
<div>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>

<div>
<button onClick={handlePrevPage} disabled={currentPage === 1}>
Previous
</button>

{Array.from({ length: totalPages }, (_, index) => (
<button
key={index}
onClick={() => handlePageChange(index + 1)}
className={currentPage === index + 1 ? 'active' : ''}
>
{index + 1}
</button>
))}

<button onClick={handleNextPage} disabled={currentPage === totalPages}>
Next
</button>
</div>
</div>
);
}

export default PaginationExample;

Explanation of Code:

  • currentItems: Filters the data array to display only the items for the current page.
  • totalPages: Calculates the number of pages by dividing the total items by itemsPerPage.
  • Navigation Functions: handleNextPage and handlePrevPage increment or decrement the currentPage value while preventing it from exceeding boundaries.
  • Page Buttons: A loop generates page numbers for navigation, setting the current page upon button click.

Styling the Pagination Component

You can style the pagination controls for a better user experience:

button {
margin: 0 5px;
padding: 5px 10px;
cursor: pointer;
}

button.active {
background-color: #007bff;
color: white;
}

Using React-Paginate Library

For more advanced features, the React-Paginate library is an excellent choice. It provides customizable pagination controls, supports various configurations and handles navigation effectively.

  1. Installation: To install React-Paginate, run:bashCopy codenpm install react-paginate
  2. Usage: After installation, import and configure React-Paginate in your component.
import React, { useState } from 'react';
import ReactPaginate from 'react-paginate';

function PaginatedComponent({ data }) {
const [currentPage, setCurrentPage] = useState(0);
const itemsPerPage = 5;

// Calculate the data for the current page
const offset = currentPage * itemsPerPage;
const currentItems = data.slice(offset, offset + itemsPerPage);
const pageCount = Math.ceil(data.length / itemsPerPage);

const handlePageClick = ({ selected }) => {
setCurrentPage(selected);
};

return (
<div>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>

<ReactPaginate
previousLabel={'Previous'}
nextLabel={'Next'}
breakLabel={'...'}
pageCount={pageCount}
marginPagesDisplayed={2}
pageRangeDisplayed={3}
onPageChange={handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
</div>
);
}

export default PaginatedComponent;

Explanation of Code:

  • ReactPaginate Component: The library component handles pagination UI with various props:
    • previousLabel and nextLabel: Set labels for navigation buttons.
    • pageCount: Determines the total number of pages.
    • onPageChange: Updates the currentPage when a page is selected.
    • containerClassName and activeClassName: Add CSS classes to customize pagination styling.

Styling with React-Paginate

You can style the pagination component by adding CSS classes as follows:

.pagination {
display: flex;
list-style: none;
padding: 0;
}

.pagination li {
margin: 0 5px;
}

.pagination li a {
text-decoration: none;
padding: 8px 12px;
color: black;
border: 1px solid #ddd;
}

.pagination li a.active {
background-color: #007bff;
color: white;
border-color: #007bff;
}

Key Differences Between Custom and React-Paginate Pagination

FeatureCustom PaginationReact-Paginate
Ease of UseManual setup and codingSimple setup with ready-made features
CustomizationFully customizableCustomizable but within library limits
Navigation OptionsBasic navigation, page numbers, next/prev buttonsAdditional features like breaks, jump to page
PerformanceLightweight, no dependenciesMight add minor weight but highly optimized

Leave a Comment