Controlled boundaries
Let the parent own the current page and disable the first and last boundary links. Boundary links combine aria-disabled, tabIndex -1 and a cancelled click, because aria-disabled alone does not stop an anchor.
"use client"
import * as React from "react"
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination"
const TOTAL_PAGES = 5
export function PaginationControlledBoundaries() {
// Page state belongs to the consumer (usually the router or a query param).
const [page, setPage] = React.useState(1)
const isFirst = page === 1
const isLast = page === TOTAL_PAGES
function goTo(event: React.MouseEvent<HTMLAnchorElement>, target: number) {
// Stand-in for client-side routing; a real app lets the router handle the href.
event.preventDefault()
if (target < 1 || target > TOTAL_PAGES) return
setPage(target)
}
return (
<div className="flex w-full flex-col gap-8">
<Pagination aria-label="Invoice pages">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
href={`#page-${Math.max(1, page - 1)}`}
aria-disabled={isFirst || undefined}
tabIndex={isFirst ? -1 : undefined}
className="transition-none aria-disabled:pointer-events-none aria-disabled:text-disabled-300"
onClick={(event) => goTo(event, page - 1)}
/>
</PaginationItem>
{Array.from({ length: TOTAL_PAGES }, (_, index) => index + 1).map((value) => (
<PaginationItem key={value}>
<PaginationLink
href={`#page-${value}`}
aria-label={`Page ${value}`}
isActive={page === value}
onClick={(event) => goTo(event, value)}
>
{value}
</PaginationLink>
</PaginationItem>
))}
<PaginationItem>
<PaginationNext
href={`#page-${Math.min(TOTAL_PAGES, page + 1)}`}
aria-disabled={isLast || undefined}
tabIndex={isLast ? -1 : undefined}
className="transition-none aria-disabled:pointer-events-none aria-disabled:text-disabled-300"
onClick={(event) => goTo(event, page + 1)}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)
}