Pagination is a common feature in web applications, allowing users to navigate through large sets of data easily. In this guide, we’ll implement pagination in a React application using React Hooks and the react-paginate library.
Prerequisites
Before we dive into the implementation, ensure you have the following:
- Node.js and npm installed on your system.
- A React application set up. If you don’t have one, you can create it using
create-react-app.
Step 1: Install react-paginate
First, you need to install the react-paginate library. Open your terminal and run the following command:
npm install react-paginate
Step 2: Set Up Your React Component
We’ll create a component to handle pagination. Here’s a basic example:
import React, { useState } from 'react';
import ReactPaginate from 'react-paginate';
// Sample data
const data = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
const ITEMS_PER_PAGE = 10;
const PaginationExample = () => {
const [currentPage, setCurrentPage] = useState(0);
// Calculate the items to display on the current page
const offset = currentPage * ITEMS_PER_PAGE;
const currentItems = data.slice(offset, offset + ITEMS_PER_PAGE);
// Handle page click
const handlePageClick = (event) => {
const selectedPage = Number(event.selected);
setCurrentPage(selectedPage);
};
return (
<div>
<h1>Pagination Example</h1>
<ul>
{currentItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<ReactPaginate
previousLabel={'Previous'}
nextLabel={'Next'}
breakLabel={'...'}
pageCount={Math.ceil(data.length / ITEMS_PER_PAGE)}
marginPagesDisplayed={2}
pageRangeDisplayed={5}
onPageChange={handlePageClick}
containerClassName={'pagination'}
activeClassName={'active'}
/>
</div>
);
};
export default PaginationExample;
Explanation
- State Management: We use
useStateto manage the current page. ThecurrentPagestate determines which items to display. - Data Calculation: We calculate the items to display on the current page using the
offsetvariable. - Pagination Component:
ReactPaginatehandles the pagination controls. We configure it to show pagination buttons, including ‘Previous’ and ‘Next’ labels. - Page Click Handler: The
handlePageClickfunction updates thecurrentPagestate based on user interaction.
Styling the Pagination
To style the pagination component, add the following CSS to your stylesheet:
.pagination {
display: flex;
list-style-type: none;
padding: 0;
margin: 20px 0;
}
.pagination li {
margin: 0 5px;
}
.pagination .active {
font-weight: bold;
}
This will ensure that your pagination controls are displayed neatly and are easy to navigate.
Conclusion
In this guide, we’ve implemented a simple pagination feature in a React application using React Hooks and react-paginate. This setup allows users to navigate through data efficiently, enhancing the user experience of your application.
Feel free to adjust the ITEMS_PER_PAGE constant and CSS styles to fit your specific needs.
