Command palette

@yasinsensoy/web

Web · Components

Pagination

Pagination: numbered pages, previous/next, first/last, page size, "go to page", a record summary and "show more" in one component.

21 exports

Live example

Preview

Code

import { Pagination } from "@yasinsensoy/web";

const [page, setPage] = useState(1);

<Pagination
  page={page}
  total={245}
  onPageChange={setSayfa}
/>

Events

  1. Events appear here when you interact with the preview.

In a table: sorting + page size + summary (Table pagination)

OrdersStatus
#4200Ayşe YılmazPaid$120.00
#4201Mehmet KayaReturned$3,239.00
#4202Zeynep DemirPaid$1,558.00
#4203Can ŞahinPaid$4,677.00
#4204Elif ÇelikPending$2,996.00
#4205Emre AkPaid$1,315.00
#4206Ayşe YılmazPaid$4,434.00
#4207Mehmet KayaPaid$2,753.00
#4208Zeynep DemirPending$1,072.00
#4209Can ŞahinPaid$4,191.00

1–10 of 137

Per page

Your own grid: usePagination, scrolls to the top of the list on change

Product 1

Product 2

Product 3

Product 4

Product 5

Product 6

Product 7

Product 8

1–8 of 58

Per page

Cursor API, total unknown: useCursorPagination

Show more (variant="more"), async

Narrow card: compact, pick by searching across 10,000 pages

Archive

Linked: Next.js server component, page from the URL (?page=)

A table paged on the server; pages are real links, the filter parameter is kept, on the first page ?page=1 isn't written.

Open the server example

Simple, with text: previous / next

Import

import {
  Pagination,
  usePagination,
  useCursorPagination,
  readPageParam,
  paginationRange,
  pageHref,
  getPageInfo,
  paginate,
} from "@yasinsensoy/web";

Pagination

componentClient component

Pagination: numbered pages, previous/next, first/last, page size, "go to page", a record summary and "show more" in one component.

It works in three ways:

  • Buttons (uncontrolled or page + onPageChange): data changes in the browser or via a request. If onPageChange returns a Promise, the clicked button shows loading. For pagination in the browser see usePagination.
  • Linked (searchParams or href): each page is a real link; in a Next.js server component the data is paginated on the server, search engines see all pages and filter parameters are kept.
  • Cursor / unknown total (hasNext): only previous/next; for a cursor stack see useCursorPagination.

Details:

  • The button count stays constant while the page changes; buttons don't slide from under the cursor. Clicking a (…) gap jumps a few pages.
  • On phones (responsive) it becomes "‹ [3 ▾] / 10 ›"; any page is picked by searching in the middle box. Touch targets are at least 44 px.
  • When the page size changes, the current first record stays visible.
  • Page changes are announced to screen readers; the current page carries aria-current="page".
  • Built-in integrations: Table pagination, Gallery pageSize.

It is a client component; in server components it can be used in linked form (searchParams, a string href) without passing functions.

Pagination({ page: pageProp, defaultPage, onPageChange, total, pageCount: pageCountProp, hasNext: hasNextProp, pageSize: pageSizeProp, defaultPageSize, onPageSizeChange, pageSizeOptions, variant: variantProp, siblings, boundaries, firstLast, jumper, summary, responsive, size, activeVariant, align: alignProp, hideOnSinglePage, disabled, scrollTo, href, searchParams, searchParam, pageSizeParam, pathname, label, classNames, className, ...props }: PaginationProps): JSX.Element | null

Examples

// Uncontrolled, in the browser:
const { items, props } = usePagination({ items: products, pageSize: 12 });
<ProductGrid products={items} />
<Pagination {...props} />

// Data from the server, async:
<Pagination
  page={page}
  total={total}
  pageSize={size}
  pageSizeOptions={[10, 20, 50]}
  onPageChange={async (p) => { await load(p, size); setPage(p); }}
  onPageSizeChange={setSize}
  summary
  jumper
/>

// Next.js server component, linked:
<Pagination total={total} pageSize={20} searchParams={await searchParams} />

// Cursor API:
const pagination = useCursorPagination<string>();
<Pagination {...pagination.props(data?.nextCursor)} />

Keeps the page and page size state; if an array is given it slices the current page. For paginating content you render yourself, like a card grid or list, with Pagination.

When the record count drops (e.g. a filter) the page is pulled to the last valid page.

usePagination({ items, total: totalProp, defaultPage, pageSize: initialSize, pageSizeOptions, onPageChange, onPageSizeChange, }?: UsePaginationOptions<T>): UsePaginationResult<T>

Examples

const pagination = usePagination({ items: products, pageSize: 12, pageSizeOptions: [12, 24, 48] });
<div className="grid grid-cols-3 gap-4">
  {pagination.items.map((p) => <ProductCard key={p.id} product={p} />)}
</div>
<Pagination {...pagination.props} summary />

Cursor pagination: the API returns a "next cursor" and the total is unknown. Cursors of visited pages are stored, so "Previous" and "First page" work without rebuilding a request chain.

useCursorPagination(initialCursor?: C): UseCursorPaginationResult<C>

Examples

const pagination = useCursorPagination<string>();
const { data } = useSWR(["/api/records", pagination.cursor], fetcher);
<Pagination {...pagination.props(data?.nextCursor)} firstLast />

Reads a positive integer from the parameters (e.g. ?page=3 → 3). Returns undefined if invalid or missing.

readPageParam(searchParams: SearchParamsRecord | URLSearchParams | undefined, name: string): number | undefined

Examples

const page = readPageParam(await searchParams, "page") ?? 1;

Produces the order of page buttons: the first and last pages, the current page and its neighbours, and the gaps (…) between them.

The array length doesn't change as the page changes (with enough pages it is always 2 × siblings + 2 × boundaries + 3), so buttons don't shift under the pointer. If a gap would hide a single page, that page is shown instead.

paginationRange({ page, pageCount, siblings, boundaries, }: PaginationRangeOptions): PaginationRangeItem[]

Examples

paginationRange({ page: 6, pageCount: 20 }) // [1, "start-gap", 5, 6, 7, "end-gap", 20]
paginationRange({ page: 2, pageCount: 20 }) // [1, 2, 3, 4, 5, "end-gap", 20]

pageHref

function

Generates the URL of a page. Existing parameters (filter, sort) are kept; on the first page the page parameter is removed so the same page doesn't have two URLs (SEO).

pageHref({ page, pageSize, href, searchParams, searchParam, pageSizeParam, defaultPageSize, pathname, }: PageHrefOptions): string

Examples

pageHref({ page: 3, searchParams: { q: "pen", page: "2" } }) // "?q=pen&page=3"
pageHref({ page: 1, searchParams: { q: "pen", page: "2" } }) // "?q=pen"
pageHref({ page: 4, href: "/blog/page/{page}" })             // "/blog/page/4"

getPageInfo

function

Computes the record range from a page number. Used when writing queries on the server and in summaries like "1–20 / 245".

getPageInfo({ page, pageSize, total }: PageInfoOptions): PageInfo

Examples

// app/products/page.tsx (server component)
const { offset, pageSize } = getPageInfo({ page: Number(sp.page ?? 1), pageSize: 20, total });
const products = await db.product.findMany({ skip: offset, take: pageSize });

paginate

function

Returns one page of an array (pagination in the browser or on the server).

paginate(items: readonly T[], page: number, pageSize: number): T[]

Examples

paginate(products, 2, 20) // products 21–40

Look of the pagination.

  • "pages": Numbered pages with (…) gaps in between and previous/next on both sides. If the total is unknown, the seen pages and (…) are shown.
  • "simple": Only "‹ Previous" and "Next ›" with "Page 3 / 10" in the middle. For cursor pagination and lists with an unknown total.
  • "compact": "‹ [3 ▾] / 10 ›"; any page is picked from the box in the middle (searchable even with thousands of pages). For narrow areas and phones.
  • "more": A "Show more" button, how many are shown and a progress bar. The next page is appended below the old ones (e-commerce lists).
type PaginationVariant = "pages" | "simple" | "compact" | "more"

Classes that can be passed to the inner parts of Pagination.

NameTypeDescription
nav?stringThe <nav> carrying the page buttons.
item?stringEach page, previous/next and gap button.
active?stringButton of the current page.
summary?stringThe "1–20 / 245" summary.
pageSize?stringPage size picker.
jumper?string"Go to page" field.

Props of the Pagination component.

Extends: Omit<ComponentProps<"div">, "children" | "onChange">

NameTypeDefaultDescription
page?numberCurrent page when controlled (starts at 1). In linked use it is read from searchParams if given; you don't need to pass it.
defaultPage?number1Initial page when uncontrolled.
onPageChange?(page: number) => unknownCalled when the page changes (in controlled and uncontrolled use). If it returns a Promise (e.g. an async function fetching data), a loading spinner turns on the clicked button until it settles and new clicks wait. In linked use it is only informational (e.g. analytics).
total?numberTotal record count. The page count is computed with pageSize; the summary ("1–20 / 245") and the "more" look use it.
pageCount?numberTotal page count (instead of total).
hasNext?booleanfalseIf the total is unknown (no total or pageCount; e.g. a cursor API), is there a next page? See useCursorPagination.
pageSize?numberRecords per page when controlled.
defaultPageSize?numberpageSizeOptions[0]` or `10Records per page when uncontrolled.
onPageSizeChange?(pageSize: number) => unknownCalled when the page size changes. The page also changes so the first record of the previous page stays visible (e.g. page 3 × 10 → page 2 × 20) and onPageChange is called as well.
pageSizeOptions?readonly number[]If given, a "Per page [20 ▾]" picker appears (e.g. [10, 20, 50, 100]).
variant?PaginationVariant"pages"` (`"simple"` if the total is unknown)Look. See PaginationVariant.
siblings?number1Number of pages shown on each side of the current page.
boundaries?number1Number of pages always shown at the start and end.
firstLast?booleanfalse« » buttons going to the first and last page.
jumper?booleanfalse"Go to page" field: type a number and press Enter to go to that page. Not shown if the total is unknown.
summary?boolean | ((info: PageInfo) => ReactNode)falseRecord range summary ("1–20 of 245"). Requires total. With a function you generate the text. See PageInfo.
responsive?booleantrueThe "pages" look becomes "compact" automatically on small screens (below 640 px); texts get shorter. Done with CSS only; renders correctly on the server too.
size?Size"md"Button size.
activeVariant?Extract<ButtonVariant, "solid" | "soft" | "outline">"soft"Button style of the current page.
align?"start" | "center" | "end" | "between""between"` if there is a summary or page size, otherwise `"center"Layout of the parts. "between": the summary and page size on the left, the pages on the right.
hideOnSinglePage?booleanfalseRenders nothing when there is a single page.
disabled?booleanAll buttons are disabled (e.g. while data loads).
scrollTo?RefObject<HTMLElement | null> | stringWhen the page changes (in button use), scrolls to this element if its top has gone above the screen: a ref or a CSS selector ("#list").
href?string | ((page: number, pageSize: number) => string)Linked use: pages become links rather than buttons (with the UIProvider link component, e.g. Next.js Link); search engines can crawl all pages and pages can open in a new tab. - A string pattern: {page} and {pageSize} are replaced with numbers ("/blog/page/{page}"). Can be given from a server component too. - A function: (page, pageSize) => url (in client components only). For working with address bar parameters, searchParams is easier.
searchParams?SearchParamsRecordLinked use: the page's URL parameters (the Next.js page's await searchParams). When given, the current page is read from searchParam, other parameters (filter, sort) are kept in the links and ?page=1 isn't written on the first page.
searchParam?string"page"Name of the page parameter.
pageSizeParam?stringName of the page size parameter. If given, the page size is also read from and written to the URL (e.g. "pageSize" → ?pageSize=50).
pathname?stringPath used in links (e.g. "/products"). If omitted, links consist only of the query ("?page=2") and resolve against the current path.
label?string"Sayfalar"Screen reader name of the page buttons region.
classNames?PaginationClassNamesClasses added to the inner parts. See PaginationClassNames.

usePagination options.

NameTypeDefaultDescription
items?readonly T[]All records to paginate in the browser. If given, the returned items is the current page and total is computed from it.
total?numberTotal records (for server pagination; when items isn't given).
defaultPage?number1Initial page.
pageSize?numberpageSizeOptions[0]` or `10Initial page size.
pageSizeOptions?readonly number[]Page size options; passed through to Pagination.
onPageChange?(page: number) => unknownWhen the page changes (e.g. to fetch data).
onPageSizeChange?(pageSize: number) => unknownWhen the page size changes.

Return value of usePagination.

Extends: PageInfo

NameTypeDescription
itemsT[]Records of the current page (if items was given).
setPage(page: number) => voidChanges the page.
setPageSize(pageSize: number) => voidChanges the page size; moves to the page where the first record stays visible.
props{ page: number; total: number | undefined; pageSize: number; pageSizeOptions: readonly number[] | undefined; onPageChange: (page: number) => unknown; onPageSizeChange: (pageSize: number) => void; }Props to spread onto Pagination: <Pagination {...props} />.

Return value of useCursorPagination.

NameTypeDescription
cursorC | undefinedCursor of the current page; initialCursor on the first page (usually undefined).
pagenumberThe current page (starts at 1).
reset() => voidReturns to the first page (e.g. when a filter changes).
props(nextCursor: C | null | undefined) => { page: number; hasNext: boolean; onPageChange: (page: number) => void; }Props to spread onto Pagination. Pass the "next cursor" from the last response; if null/undefined there is no next page.

Gap (…) showing pages hidden between page buttons.

type PaginationGap = "start-gap" | "end-gap"

An element of the paginationRange array: a page number or a gap.

type PaginationRangeItem = number | PaginationGap

Address bar parameters; a Next.js page's searchParams is in this shape. Can be passed from the server to a client component (a plain object).

type SearchParamsRecord = Readonly<Record<string, string | readonly string[] | undefined>>

paginationRange options.

NameTypeDefaultDescription
pagenumberCurrent page (starts at 1).
pageCountnumberTotal page count.
siblings?number1Number of pages shown on each side of the current page.
boundaries?number1Number of pages always shown at the start and end.

pageHref options.

NameTypeDefaultDescription
pagenumberPage to go to.
pageSize?number | undefinedRecords per page; for {pageSize} in the href pattern and for pageSizeParam.
href?string | undefinedURL pattern: {page} and {pageSize} are replaced with numbers (e.g. "/blog/page/{page}"). If given, the other options are ignored.
searchParams?SearchParamsRecord | undefinedExisting parameters to keep (e.g. filters).
searchParam?string | undefined"page"Name of the page parameter.
pageSizeParam?string | undefinedName of the page size parameter. If given, pageSize is also written to the URL (not written if it equals defaultPageSize).
defaultPageSize?number | undefinedDefault page size that isn't written to the URL.
pathname?string | undefinedPath of the URL (e.g. "/products"). If omitted, the URL consists only of the query ("?page=2") and the browser resolves it against the current path.

getPageInfo options.

NameTypeDescription
pagenumberRequested page (starts at 1). Clamped to the nearest valid page when out of range.
pageSizenumberRecords per page.
total?number | undefinedTotal records. Omitted when unknown (cursor pagination).

PageInfo

interface

Position of a page; returned by getPageInfo.

NameTypeDescription
pagenumberPage clamped to the valid range (starts at 1).
pageSizenumberRecords per page.
totalnumber | undefinedTotal records; undefined when unknown.
pageCountnumber | undefinedTotal pages; undefined when the total is unknown. 1 when there are no records.
offsetnumberNumber of records to skip (SQL OFFSET, Array.slice start).
startnumberIndex of the first record on the page (starts at 1); 0 without records.
endnumberIndex of the last record on the page; offset + pageSize when the total is unknown.
hasPreviousbooleanIs there a previous page?
hasNextbooleanIs there a next page? true when the total is unknown.