Pagination displays a subset of data with navigation controls.
Code — Client-side:
1import { useState } from "react";23function PaginatedList({ items, itemsPerPage = 10 }) {4 const [currentPage, setCurrentPage] = useState(1);5 const totalPages = Math.ceil(items.length / itemsPerPage);67 const startIndex = (currentPage - 1) * itemsPerPage;8 const currentItems = items.slice(startIndex, startIndex + itemsPerPage);910 return (11 <div>12 <ul>13 {currentItems.map(item => (14 <li key={item.id}>{item.name}</li>15 ))}16 </ul>1718 <div className="pagination">19 <button20 onClick={() => setCurrentPage(p => p - 1)}21 disabled={currentPage === 1}22 >23 Previous24 </button>2526 {Array.from({ length: totalPages }, (_, i) => (27 <button28 key={i + 1}29 onClick={() => setCurrentPage(i + 1)}30 className={currentPage === i + 1 ? "active" : ""}31 >32 {i + 1}33 </button>34 ))}3536 <button37 onClick={() => setCurrentPage(p => p + 1)}38 disabled={currentPage === totalPages}39 >40 Next41 </button>42 </div>43 </div>44 );45}
Code — Server-side (Next.js):
1async function Products({ searchParams }) {2 const page = Number(searchParams.page) || 1;3 const products = await fetchProducts({ page, limit: 10 });45 return (6 <div>7 <ProductList products={products} />8 <Pagination9 currentPage={page}10 totalPages={products.totalPages}11 />12 </div>13 );14}
Best practices: