Pagination bar
A pagination bar with page numbers and ellipses (a fixed number of slots, so it doesn't shift as you page), previous and next buttons, a rows-per-page select that keeps the current first row in view, and a "41–60 of 312" summary announced on change. In narrow containers the numbers collapse to "Page 3 of 16" using container queries. Renders buttons, or real links when given getPageHref.
Source
"use client";
import { useId, type ReactNode } from "react";
import { ChevronDown, ChevronLeft, ChevronRight, Ellipsis } from "lucide-react";
import { cn } from "@/lib/utils";
export type PageSlot = number | "gap";
/**
* Page numbers to show: always the first and last page, the current page with `siblings` on each side, and gaps.
* The number of slots stays the same as you move through the pages, so the bar does not jump around.
*/
export function paginationRange(page: number, totalPages: number, siblings = 1): PageSlot[] {
const slots = siblings * 2 + 5;
const range = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => from + i);
if (totalPages <= slots) return range(1, totalPages);
const left = Math.max(page - siblings, 1);
const right = Math.min(page + siblings, totalPages);
const gapLeft = left > 3;
const gapRight = right < totalPages - 2;
if (!gapLeft) return [...range(1, slots - 2), "gap", totalPages];
if (!gapRight) return [1, "gap", ...range(totalPages - (slots - 3), totalPages)];
return [1, "gap", ...range(left, right), "gap", totalPages];
}
export interface PaginationBarProps {
/** Current page, starting at 1. */
page: number;
pageSize: number;
total: number;
onPageChange: (page: number) => void;
/** Shows the page-size select. The current first row stays in view when the size changes. */
onPageSizeChange?: (pageSize: number) => void;
pageSizeOptions?: number[];
/** Page numbers shown on each side of the current one. */
siblings?: number;
/** Render real links (good for SEO and opening in a new tab) instead of buttons. */
getPageHref?: (page: number) => string;
className?: string;
}
const control =
"inline-flex h-9 items-center justify-center rounded-md text-sm font-medium outline-hidden transition-colors " +
"focus-visible:ring-[3px] focus-visible:ring-ring/50 [&_svg]:size-4 [&_svg]:shrink-0";
function PageControl({
page, disabled, current, label, href, onSelect, className, children,
}: {
page: number;
disabled?: boolean;
current?: boolean;
label: string;
href?: string;
onSelect: (page: number) => void;
className?: string;
children: ReactNode;
}) {
const shared = {
"aria-label": label,
"aria-current": current ? ("page" as const) : undefined,
className: cn(control, disabled && "pointer-events-none opacity-40", className),
};
if (href !== undefined) {
return disabled ? (
<a {...shared} aria-disabled="true" role="link">{children}</a>
) : (
<a {...shared} href={href} onClick={() => onSelect(page)}>{children}</a>
);
}
return (
<button {...shared} type="button" disabled={disabled} onClick={() => onSelect(page)}>
{children}
</button>
);
}
export function PaginationBar({
page, pageSize, total, onPageChange, onPageSizeChange, pageSizeOptions = [10, 20, 50, 100], siblings = 1, getPageHref, className,
}: PaginationBarProps) {
const id = useId();
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const current = Math.min(Math.max(1, page), totalPages);
const first = total === 0 ? 0 : (current - 1) * pageSize + 1;
const last = Math.min(current * pageSize, total);
const format = (value: number) => value.toLocaleString();
const go = (next: number) => {
if (next !== current && next >= 1 && next <= totalPages) onPageChange(next);
};
function changeSize(size: number) {
onPageSizeChange?.(size);
// Keep the row that was at the top of the page visible.
onPageChange(Math.floor((first > 0 ? first - 1 : 0) / size) + 1);
}
return (
<nav aria-label="Pagination" className={cn("@container", className)}>
<div className="flex flex-col gap-3 @3xl:flex-row @3xl:items-center @3xl:justify-between">
<div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 @3xl:justify-start">
<p aria-live="polite" className="text-sm tabular-nums text-muted-foreground">
<span className="font-medium text-foreground">{format(first)}–{format(last)}</span> of{" "}
<span className="font-medium text-foreground">{format(total)}</span>
</p>
{onPageSizeChange && (
<div className="flex items-center gap-2">
<label htmlFor={`${id}-size`} className="text-sm text-muted-foreground">Rows per page</label>
<div className="relative">
<select
id={`${id}-size`}
value={pageSize}
onChange={(event) => changeSize(Number(event.target.value))}
className={cn(
"h-8 cursor-pointer appearance-none rounded-md border border-input bg-background pl-2.5 pr-7 text-sm tabular-nums text-foreground",
"shadow-xs outline-hidden transition-[border-color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40",
"dark:bg-input/20 [&>option]:bg-popover [&>option]:text-popover-foreground",
)}
>
{pageSizeOptions.map((size) => <option key={size} value={size}>{size}</option>)}
</select>
<ChevronDown aria-hidden="true" className="pointer-events-none absolute right-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
</div>
</div>
)}
</div>
<div className="flex items-center justify-between gap-1 @lg:justify-start">
<PageControl
page={current - 1}
label="Previous page"
disabled={current <= 1}
href={getPageHref?.(Math.max(1, current - 1))}
onSelect={go}
className="gap-1 pl-2 pr-3 text-foreground hover:bg-accent"
>
<ChevronLeft aria-hidden="true" />
<span>Previous</span>
</PageControl>
{/* Narrow containers: a plain "Page x of y" instead of the number list. */}
<span className="px-2 text-sm tabular-nums text-muted-foreground @lg:hidden">
Page <span className="font-medium text-foreground">{current}</span> of {totalPages}
</span>
<ul className="hidden items-center gap-1 @lg:flex">
{paginationRange(current, totalPages, siblings).map((slot, index) =>
slot === "gap" ? (
<li key={`gap-${index}`} aria-hidden="true" className="grid size-9 place-items-center text-muted-foreground">
<Ellipsis className="size-4" />
</li>
) : (
<li key={slot}>
<PageControl
page={slot}
label={`Page ${slot}`}
current={slot === current}
href={getPageHref?.(slot)}
onSelect={go}
className={cn(
"min-w-9 px-2 tabular-nums",
slot === current
? "border border-border bg-background font-semibold text-foreground shadow-xs dark:border-input dark:bg-input/30"
: "text-muted-foreground hover:bg-accent hover:text-foreground",
)}
>
{slot}
</PageControl>
</li>
),
)}
</ul>
<PageControl
page={current + 1}
label="Next page"
disabled={current >= totalPages}
href={getPageHref?.(Math.min(totalPages, current + 1))}
onSelect={go}
className="gap-1 pl-3 pr-2 text-foreground hover:bg-accent"
>
<span>Next</span>
<ChevronRight aria-hidden="true" />
</PageControl>
</div>
</div>
</nav>
);
}
