Pagination Control
This document presents a reusable React component for navigating through paginated results. It includes an API description, props, usage examples, and responsive adaptation scenarios.
PaginationControl Element
The PaginationControl provides a clean and accessible user interface for navigating through multiple pages of content. It integrates with Next.js routing and dynamically reflects the current page using URL parameters (such as ?page=2).
File Location
/components/PaginationControl.tsx
Purpose
This component:
- Displays navigation buttons (first, previous, numbered, next, last)
- Enables/disables navigation based on the current page
- Highlights the active page
- Uses
makeURL()to generate links with URL parameters
| Name | Type | Description |
|---|---|---|
totalPages | number | The total number of pages in the dataset or query |
How It Works
- Reading the Current Page from the URL
const router = useRouter();
const searchParams = new URLSearchParams(router.asPath.split("?")[1] || "");
const currentPage = parseInt(searchParams.get("page") || "1", 10);
- Extracts the page parameter from the URL.
- Returns 1 if it doesn't exist.
- Ensures the page is at least 1.
- Navigation Calculation
const prevPage = Math.max(page - 1, 1);
const nextPage = page + 1 <= totalPages ? page + 1 : totalPages;
- Calculates previous and next pages with boundary checks.
- Creating Visible Page Numbers
const pageNumbers = Array.from({ length: 5 }, (_, i) => page + i - 2).filter(
(p) => p >= 1 && p <= totalPages,
);
- Creates a list of 5 page numbers centered around the current page.
Component Structure
PaginationControl
<NavigationLink disabled={page === 1} href={...} icon={ChevronDoubleLeftIcon} />
<NavigationLink disabled={page === 1} href={...} icon={ChevronLeftIcon} />
{pageNumbers.map(pageNumber => (
<Link key={pageNumber} href={...}>{pageNumber}</Link>
))}
<NavigationLink disabled={page === totalPages} href={...} icon={ChevronRightIcon} />
<NavigationLink disabled={page === totalPages} href={...} icon={ChevronDoubleRightIcon} />
- Displays 5 navigation controls:
- First page (
<<)- Previous (
<)- Page numbers (
1,2,3, ...)- Next (
>)- Last (
>>)- Each
hrefis built usingmakeURL()to preserve URL parameters and update only thepage.
NavigationLink
<Link className={...} href={href} aria-label={ariaLabel}>
<Icon className="w-5 h-5" />
<span className="sr-only">{ariaLabel}</span>
</Link>
- Abstract component for navigation buttons.
- Takes:
disabled: to disable when necessaryhref: the target URLariaLabel: for accessibilityicon: an icon from Heroicons
Example
If the URL is:
/services?page=3
The component:
- Highlights page 3
- Enables "Previous" and "First"
- Disables "Next" and "Last" if
totalPages = 3 - Generates pages: 1, 2, 3 (centered on 3)
Dependencies
next/router: for routing and parametersclassnames (cn): for dynamicclass names@heroicons/react: for navigation iconsmakeURL: helper function for updating URLs
