How to Create Pagination in React: Simple Guide with Example
To create pagination in React, use
useState to track the current page and slice your data array to show only items for that page. Render page numbers as buttons and update the current page state on click to display new data.Syntax
Pagination in React typically involves these parts:
useStateto store the current page number.- Slicing the data array to show only items for the current page.
- Buttons or links to change the current page.
This pattern helps show a small part of data at a time and lets users navigate pages.
javascript
const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 5; const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = data.slice(indexOfFirstItem, indexOfLastItem); // Render currentItems and page buttons <button onClick={() => setCurrentPage(pageNumber)}>Page {pageNumber}</button>
Example
This example shows a list of 20 items with pagination that displays 5 items per page. Users can click page numbers to see different items.
javascript
import React, { useState } from 'react'; const PaginationExample = () => { const data = Array.from({ length: 20 }, (_, i) => `Item ${i + 1}`); const [currentPage, setCurrentPage] = useState(1); const itemsPerPage = 5; const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = data.slice(indexOfFirstItem, indexOfLastItem); const totalPages = Math.ceil(data.length / itemsPerPage); return ( <div> <ul> {currentItems.map(item => ( <li key={item}>{item}</li> ))} </ul> <div> {[...Array(totalPages)].map((_, i) => ( <button key={i + 1} onClick={() => setCurrentPage(i + 1)} aria-label={`Go to page ${i + 1}`} style={{ margin: '0 5px', backgroundColor: currentPage === i + 1 ? '#007bff' : '#eee', color: currentPage === i + 1 ? '#fff' : '#000', border: 'none', padding: '5px 10px', cursor: 'pointer' }} > {i + 1} </button> ))} </div> </div> ); }; export default PaginationExample;
Output
A list showing 5 items (e.g., Item 1 to Item 5) and below it page buttons 1 2 3 4 that highlight the current page. Clicking a page button updates the list to show that page's items.
Common Pitfalls
Common mistakes when creating pagination in React include:
- Not updating the current page state correctly, causing the UI not to refresh.
- Not calculating the slice indexes properly, leading to wrong items shown.
- Not handling edge cases like empty data or page numbers out of range.
- Using indexes as keys in lists when data can change, which can cause rendering issues.
Always ensure page buttons update state and data slicing matches the current page.
javascript
/* Wrong: Using data index as key and not updating state properly */ {data.map((item, index) => ( <li key={index}>{item}</li> // index as key can cause issues ))} <button onClick={() => setCurrentPage(currentPage)}>Page 1</button> // no change in state /* Right: Use unique keys and update state correctly */ {currentItems.map(item => ( <li key={item}>{item}</li> ))} <button onClick={() => setCurrentPage(1)}>Page 1</button>
Quick Reference
- useState: Store current page number.
- slice(): Extract items for current page.
- Math.ceil(): Calculate total pages.
- Buttons: Change current page on click.
- Keys: Use unique keys for list items.
Key Takeaways
Use React's useState to track the current page number for pagination.
Slice your data array based on current page and items per page to show correct items.
Render page buttons that update the current page state on click to navigate.
Always use unique keys for list items to avoid rendering issues.
Handle edge cases like empty data and invalid page numbers gracefully.