Pagination
FreeNewNumbered pages that keep their length near either end, a previous and next pair for cursor paging, and a rows-per-page select.
Installation
pnpm dlx shadcn@latest add @viewport/pagination
First time? Add the @viewport registry to components.json. Setup takes one minute.
Usage
The code behind the preview above.
"use client";
import { useState } from "react";
import { CursorPagination, PageSize, Pagination } from "@/components/viewport/pagination";
export default function PaginationDemo() {
const [page, setPage] = useState(6);
const [size, setSize] = useState(25);
const [cursor, setCursor] = useState(0);
const total = 1284;
const pages = Math.ceil(total / size);
const current = Math.min(page, pages);
return (
<div className="flex w-full max-w-xl flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border bg-card px-4 py-3">
<PageSize
value={size}
onValueChange={(next) => {
setSize(next);
setPage(1);
}}
/>
<Pagination page={current} pageCount={pages} onPageChange={setPage} />
</div>
<div className="rounded-2xl border border-border bg-card px-4 py-3">
<CursorPagination from={cursor * 25 + 1} to={Math.min(total, cursor * 25 + 25)} total={total} noun="contacts" onPrevious={cursor > 0 ? () => setCursor((c) => c - 1) : undefined} onNext={(cursor + 1) * 25 < total ? () => setCursor((c) => c + 1) : undefined} />
</div>
</div>
);
}Props
<Pagination>
| Prop | Type | Default |
|---|---|---|
| page* | numberThe current page, starting at 1. | — |
| pageCount* | number | — |
| onPageChange* | (page: number) => void | — |
| siblings | numberHow many numbers to show on each side of the current page. | 1 |
<CursorPagination>
| Prop | Type | Default |
|---|---|---|
| onPrevious | () => voidRuns when Previous is pressed. Leave it out on the first page. | — |
| onNext | () => voidRuns when Next is pressed. Leave it out on the last page. | — |
| from* | numberThe index of the first and last row shown, and the total if it is known. | — |
| to* | number | — |
| total | number | — |
| noun | stringWhat the rows are, e.g. "contacts". | "results" |
<PageSize>
| Prop | Type | Default |
|---|---|---|
| value* | number | — |
| onValueChange* | (size: number) => void | — |
| options | number[]The sizes offered. | [10, 25, 50, 100] |
| label | stringThe text before the control. | "Rows per page" |
| className | string | — |
Accessibility
- A nav landmark; the current page has aria-current.
- Every button is named: “Page 4”, “Next page”.
- Numbers give way to “Page 3 of 12” on narrow screens.
- The range in view is announced when it changes.