React Pagination with `react-paginate`: A Simple Tutorial
Implement efficient pagination in your React applications using the `react-paginate` library. This tutorial provides a step-by-step guide with code examples, demonstrating how to display large datasets in a user-friendly and performant manner.
React Pagination with `react-paginate`
Introduction to Pagination
Pagination is crucial for displaying large datasets efficiently. Instead of showing all items at once, pagination breaks the data into smaller, manageable pages. This improves the user experience by making data easier to browse and reducing load times.
React Pagination Libraries
Several npm packages simplify pagination in React. This tutorial focuses on `react-paginate`, a lightweight and versatile library.
Installation
Installation Command
npm install react-paginate --save
Basic Usage
This example demonstrates basic pagination using `react-paginate`. Note that you'll need to add your own CSS for styling; `react-paginate` doesn't include any styles by default.
Basic Pagination Example
import React, { useState, useEffect } from 'react';
import ReactPaginate from 'react-paginate';
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
const itemsPerPage = 5;
const PaginatedItems = () => {
// ... (rest of the component from the original example)
};
ReactDOM.render(<PaginatedItems items={items} itemsPerPage={itemsPerPage} />, document.getElementById('container'));
(The complete `PaginatedItems` component from the original text is omitted here for brevity. The key concepts are: managing the current page using state, calculating the page range based on `itemsPerPage`, using `useEffect` to fetch and display data, and using `handlePageClick` to handle page changes.)
`react-paginate` Props
The `react-paginate` component offers many configurable properties (see table below). These props allow extensive customization of your pagination UI.
Prop Name | Type | Description |
---|---|---|
pageCount |
Number | Total number of pages. |
pageRangeDisplayed |
Number | Number of page numbers to display. |
marginPagesDisplayed |
Number | Number of pages to show at the beginning and end. |
onPageChange |
Function | Callback function triggered when the page is changed. |
containerClassName |
String | Class name for the pagination container. |
activeClassName |
String | Class name for the active page number. |
previousLabel |
String | Label for the "previous" button. |
nextLabel |
String | Label for the "next" button. |
breakLabel |
String | Label to display for page breaks (e.g., "..."). |
forcePage |
Number | Specifies the currently selected page. |
Example: Fetching Data and Implementing Pagination
Fetching Data and Displaying with Pagination
In this example, we demonstrate how to fetch data (e.g., from a JSON file) and display it using pagination. The core concepts are:
- Fetching data using the
useEffect
hook. - Calculating the displayed items based on the current page and
itemsPerPage
. - Updating the state when a page changes.
Step 1: Setup State and Fetch Data
We will use useState
and useEffect
to manage state and fetch data asynchronously.
import React, { useState, useEffect } from "react";
import ReactPaginate from "react-paginate";
const PaginatedData = () => {
const [data, setData] = useState([]);
const [currentPage, setCurrentPage] = useState(0);
const [itemsPerPage] = useState(10);
useEffect(() => {
// Fetch data from JSON file (or API)
fetch("/data.json")
.then((response) => response.json())
.then((data) => setData(data));
}, []);
// Calculate the items to display based on the current page and itemsPerPage
const startIndex = currentPage * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const displayedItems = data.slice(startIndex, endIndex);
const handlePageChange = (selectedPage) => {
setCurrentPage(selectedPage.selected);
};
return (
<div>
<h1>Paginated Data</h1>
<ul>
{displayedItems.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
<ReactPaginate
pageCount={Math.ceil(data.length / itemsPerPage)}
pageRangeDisplayed={2}
marginPagesDisplayed={1}
onPageChange={handlePageChange}
/>
</div>
);
};
export default PaginatedData;
Step 2: Explanation
In the above code:
- We fetch data from a JSON file using
useEffect
. - The data is divided into pages based on the
currentPage
anditemsPerPage
. - When the page is changed, the
handlePageChange
function updates the state to show the correct page of items.
Step 3: Render the Paginated Data
The data is displayed in an unordered list, with pagination controls at the bottom. The displayed items will update based on the current page, and you can navigate between pages using the pagination buttons.
Styling the Pagination
You can style the pagination using CSS classes. `react-paginate` provides props (e.g., `nextLinkClassName`, `previousLinkClassName`, `activeClassName`) to target specific elements for styling.