Pagination is essential for efficiently handling large datasets, breaking them into smaller, manageable chunks. This enhances the user experience by allowing users to navigate through content one page at a time.
Below is the implementation of a reusable Pagination Component in React.
What:
A Pagination Component in React allows:
- Displaying page numbers.
- Navigating between pages with
Previous
andNext
buttons. - Dynamically rendering the current page of data.
Why:
Pagination is crucial for handling large datasets efficiently. It reduces rendering time and load on the browser by displaying only a subset of data at a time. This improves user experience and overall performance.
How:
The solution involves two components:
-
Pagination Component: Handles pagination logic, including generating page numbers, and managing the
Previous
,Next
, and page selection. - App Component: Manages state and displays data based on the current page.
Step-by-Step Implementation
1. Create the Pagination
Component
The Pagination
component generates page numbers and includes Previous
and Next
buttons for navigation. It accepts four props:
-
totalItems
: Total number of items. -
itemsPerPage
: Number of items to display per page. -
currentPage
: The currently active page. -
onPageChange
: Callback function to handle page changes.
import React from 'react';
const Pagination = ({ totalItems, itemsPerPage, currentPage, onPageChange }) => {
const totalPages = Math.ceil(totalItems / itemsPerPage); // Calculate total number of pages
// Generate an array of page numbers
const pageNumbers = Array.from({ length: totalPages }, (_, index) => index + 1);
return (
<nav>
<ul style={{ display: 'flex', listStyle: 'none', padding: 0 }}>
<li>
<button
onClick={() => onPageChange(currentPage - 1)} // Previous button
disabled={currentPage === 1} // Disable if on the first page
>
Previous
</button>
</li>
{pageNumbers.map((number) => (
<li key={number} style={{ margin: '0 5px' }}>
<button
onClick={() => onPageChange(number)} // Page number button
style={{
padding: '5px 10px',
backgroundColor: currentPage === number ? 'lightblue' : 'white', // Highlight current page
}}
>
{number}
</button>
</li>
))}
<li>
<button
onClick={() => onPageChange(currentPage + 1)} // Next button
disabled={currentPage === totalPages} // Disable if on the last page
>
Next
</button>
</li>
</ul>
</nav>
);
};
export default Pagination;
2. Integrate Pagination into the Main Component
The App
component includes the Pagination
component and manages state to display the correct items based on the current page.
import React, { useState } from 'react';
import Pagination from './Pagination';
const App = () => {
const items = Array.from({ length: 50 }, (_, index) => `Item ${index + 1}`); // Mock data
const itemsPerPage = 5; // Items per page
const [currentPage, setCurrentPage] = useState(1); // Current page state
// Calculate indices for slicing the data based on the current page
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = items.slice(indexOfFirstItem, indexOfLastItem);
// Handle page change
const handlePageChange = (pageNumber) => {
if (pageNumber >= 1 && pageNumber <= Math.ceil(items.length / itemsPerPage)) {
setCurrentPage(pageNumber); // Update the current page
}
};
return (
<div>
<h1>Pagination Example</h1>
{/* Render Current Items */}
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
{/* Render Pagination Component */}
<Pagination
totalItems={items.length} // Total number of items
itemsPerPage={itemsPerPage} // Items per page
currentPage={currentPage} // Current page
onPageChange={handlePageChange} // Callback to handle page change
/>
</div>
);
};
export default App;
Explanation of the Code
1. Pagination Component:
- Total Pages Calculation: The total number of pages is calculated by dividing the total number of items by the items per page, rounding up if necessary.
- Page Numbers: It generates a list of page numbers for navigation.
- Previous/Next Buttons: These buttons allow users to navigate to the previous or next page. They are disabled if the user is already on the first or last page.
- Dynamic Page Highlighting: The current page is visually highlighted for better UX.
2. App Component:
-
State Management: The
currentPage
state tracks the active page. ThesetCurrentPage
function updates this state whenever a page change occurs. -
Data Slicing: The
currentItems
are dynamically calculated by slicing theitems
array based on the current page and the number of items per page. -
Handle Page Change: The
handlePageChange
function is responsible for updating thecurrentPage
when a page number is clicked or thePrevious
orNext
buttons are pressed.
Output
- The data is displayed in pages, with each page containing the specified number of items (
itemsPerPage
). - The
Pagination
component dynamically renders the page numbers and handles navigation between them. - Users can click on the
Previous
,Next
, or specific page buttons to update the displayed data.
When to Use:
This pagination logic is ideal for any scenario where you need to display large datasets efficiently, such as:
- Listings of products, articles, or users.
- Search results or API data that require efficient rendering across multiple pages.
Summary:
- What: The Pagination Component handles displaying page numbers and navigating between them, improving user experience when dealing with large datasets.
- Why: Pagination reduces load times and enhances performance by displaying data in smaller, manageable chunks.
-
How: The
Pagination
component generates page numbers and navigation buttons, while theApp
component manages the state and updates the data displayed based on the current page. - When: This pattern is useful when working with large datasets that need to be split across multiple pages for efficient rendering.
Top comments (0)