Pagination
Pagination helps users navigate large sets of data by breaking content into pages. In this guide, we’ll build a reusable Pagination component in React/Next.js that handles both the UI and the logic, making your app faster and easier to use.
Pagination preview
Please install everything that's required
Before setup and using this component, please install all the required dependencies from this link (if you have never installed).
1. Setup codes
Create a new file components/ui/Pagination.tsx, then paste the code below
jsximport { ChevronLeftIcon, ChevronRightIcon } from "@heroicons/react/24/outline"; export default function Pagination({ fromItem, toItem, totalItems, }: { fromItem: number; toItem: number; totalItems: number; }) { return ( <nav aria-label="Pagination" className="flex items-center justify-between gap-4 bg-white px-4 py-3 sm:px-6" > <div className="hidden sm:block"> <p className="text-sm text-gray-700"> Showing <span className="font-medium">{fromItem}</span> to{" "} <span className="font-medium">{toItem}</span> of{" "} <span className="font-medium">{totalItems}</span> results </p> </div> <div className="flex flex-1 justify-between sm:justify-end"> {fromItem !== 1 && ( <button className="relative inline-flex items-center gap-2 rounded-full bg-white px-3 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus-visible:outline-offset-0"> <ChevronLeftIcon className="size-4" /> Previous </button> )} {toItem !== totalItems && ( <button className="relative ml-3 inline-flex items-center gap-2 rounded-full bg-white px-3 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus-visible:outline-offset-0"> Next <ChevronRightIcon className="size-4" /> </button> )} </div> </nav> ); }
2. Usages
Now you can use Pagination component any where you want like: footer of Table, footer of Card List, ...
jsximport Table from "@components/ui/Table" import Pagination from "@components/ui/Pagination" ... export async function Dashboard() { ... return ( <> <div className="min-w-0"> <Table /> <Pagination fromItem={1} toItem={10} totalItems={26} /> </div> </> ); }
Now the UI like that