All components
Pagination
Page navigation with prev/next triggers, sibling and boundary pages, and ellipses for long ranges.
1234567891011121314151617181920212223242526import { Pagination } from "#components/ui/base-ui/pagination.tsx";import { indigoPalette } from "@stylexblocks/ui/themes/palettes.ts";
export function Example() { return ( // hand-built (Base UI has no pagination): Root owns the page state and // renders a labelled <nav>; items carry aria-current="page" and the // triggers disable at the edges. Same page range as the Ark version. <Pagination.Root count={120} pageSize={10} siblingCount={1} defaultPage={4} variant="outline" size="md" palette={indigoPalette} > <Pagination.PrevTrigger /> <Pagination.Items /> <Pagination.NextTrigger /> </Pagination.Root> );}
// custom rendering: <Pagination.Context>{(p) => p.pages.map(...)}</Pagination.Context>// controlled: <Pagination.Root page={page} onPageChange={(d) => setPage(d.page)}>Variants
outline
subtle
solid
Sizes
xs
sm
md
lg
Compact with page text
Read the state through Pagination.Context to show “Page 3 of 12” between first/prev and next/last triggers.
12345678910111213141516171819import { Pagination } from "#components/ui/base-ui/pagination.tsx";
export function Example() { return ( <Pagination.Root count={240} pageSize={20} defaultPage={3}> <Pagination.FirstTrigger /> <Pagination.PrevTrigger /> <Pagination.Context> {(pagination) => ( <Pagination.Text> Page {pagination.page} of {pagination.totalPages} </Pagination.Text> )} </Pagination.Context> <Pagination.NextTrigger /> <Pagination.LastTrigger /> </Pagination.Root> );}Controlled, slicing data
Control `page` to page through your own rows; `siblingCount={0}` keeps the range short.
Showing 1–5 of 47: INV-1001, INV-1002, INV-1003, INV-1004, INV-1005
1234567891011121314151617181920212223242526import { useState } from "react";import { Pagination } from "#components/ui/base-ui/pagination.tsx";
export function Example({ rows }: { rows: string[] }) { const [page, setPage] = useState(1); const pageSize = 5; const visible = rows.slice((page - 1) * pageSize, page * pageSize); return ( <> <ul>{visible.map((row) => <li key={row}>{row}</li>)}</ul> <Pagination.Root count={rows.length} pageSize={pageSize} siblingCount={0} page={page} onPageChange={(d) => setPage(d.page)} variant="solid" size="sm" > <Pagination.PrevTrigger /> <Pagination.Items /> <Pagination.NextTrigger /> </Pagination.Root> </> );}Install
1npx stylexblocks add paginationSource
components/ui/base-ui/pagination.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667import * as stylex from "@stylexjs/stylex";import { createContext, useContext, useMemo, useState } from "react";import { mergeProps } from "@base-ui/react/merge-props";import { useRender } from "@base-ui/react/use-render";import { createSlotRecipeContext } from "#lib/base-ui/create-slot-recipe-context.tsx";import { defineSlotRecipe, type SlotRecipeVariants, type StyleOverrideProps, type WithStyleOverrides,} from "#lib/recipe-props.ts";import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
const PAGINATION_SELECTED = ':is([data-selected], [aria-current="page"])'const PAGINATION_DISABLED = ':is(:disabled, [disabled], [data-disabled], [aria-disabled="true"])'
const paginationRoot = stylex.create({ base: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: spacing._1, },})
// Page buttons, prev/next/first/last triggers. The variants only set the// selected-state custom properties; background and text colour read them// with a fallback, so hovering the current page keeps its selected look// (a plain `:hover` condition would outrank `:is([data-selected])`).const paginationItem = stylex.create({ base: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, appearance: 'none', userSelect: 'none', borderWidth: 0, borderStyle: 'none', margin: 0, fontFamily: 'inherit', fontWeight: fontWeights.medium, fontVariantNumeric: 'tabular-nums', textDecoration: 'none', whiteSpace: 'nowrap', borderRadius: semanticRadii.control, backgroundColor: { default: `var(--pagination-item-bg, transparent)`, ':hover': `var(--pagination-item-bg, ${semanticColors.bgMuted})`, }, color: `var(--pagination-item-fg, ${semanticColors.fg})`, cursor: { default: 'pointer', [PAGINATION_DISABLED]: 'not-allowed', }, opacity: { default: null, [PAGINATION_DISABLED]: 0.5, }, transitionProperty: 'background-color, color, box-shadow', transitionDuration: durations.moderate, outlineWidth: { default: null, ':focus-visible': '2px', }, outlineOffset: { default: null, ':focus-visible': '2px', }, outlineStyle: { default: null, ':focus-visible': 'solid', }, outlineColor: { default: null, ':focus-visible': colorPalette.focusRing, }, },})
const paginationItemSizes = stylex.create({ xs: { height: sizes.controlXs, minWidth: sizes.controlXs, paddingInline: spacing._1, fontSize: fontSizes.xs, lineHeight: lineHeights.xs, }, sm: { height: sizes.controlSm, minWidth: sizes.controlSm, paddingInline: spacing._1_5, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, md: { height: sizes.controlMd, minWidth: sizes.controlMd, paddingInline: spacing._2, fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, lg: { height: sizes.controlLg, minWidth: sizes.controlLg, paddingInline: spacing._2_5, fontSize: fontSizes.md, lineHeight: lineHeights.md, },})
const paginationItemVariants = stylex.create({ solid: { '--pagination-item-bg': { default: null, [PAGINATION_SELECTED]: colorPalette.solid, [PAGINATION_DISABLED]: 'transparent', }, '--pagination-item-fg': { default: null, [PAGINATION_SELECTED]: colorPalette.contrast, }, }, subtle: { '--pagination-item-bg': { default: null, [PAGINATION_SELECTED]: `color-mix(in oklch, ${colorPalette.solid} 12%, transparent)`, [PAGINATION_DISABLED]: 'transparent', }, '--pagination-item-fg': { default: null, [PAGINATION_SELECTED]: colorPalette.fg, }, }, outline: { '--pagination-item-bg': { default: null, [PAGINATION_SELECTED]: semanticColors.bg, [PAGINATION_DISABLED]: 'transparent', }, '--pagination-item-fg': { default: null, [PAGINATION_SELECTED]: colorPalette.fg, }, boxShadow: { default: null, [PAGINATION_SELECTED]: `inset 0 0 0 1px ${colorPalette.emphasized}`, }, },})
const paginationEllipsis = stylex.create({ base: { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, userSelect: 'none', color: semanticColors.fgMuted, },})
const paginationEllipsisSizes = stylex.create({ xs: { height: sizes.controlXs, minWidth: sizes.controlXs, fontSize: fontSizes.xs, }, sm: { height: sizes.controlSm, minWidth: sizes.controlSm, fontSize: fontSizes.sm, }, md: { height: sizes.controlMd, minWidth: sizes.controlMd, fontSize: fontSizes.sm, }, lg: { height: sizes.controlLg, minWidth: sizes.controlLg, fontSize: fontSizes.md, },})
// "Page 3 of 12" style summaries for compact layouts.const paginationText = stylex.create({ base: { display: 'inline-flex', alignItems: 'center', paddingInline: spacing._2, color: semanticColors.fgMuted, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', },})
const paginationTextSizes = stylex.create({ xs: { fontSize: fontSizes.xs, lineHeight: lineHeights.xs, }, sm: { fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, md: { fontSize: fontSizes.sm, lineHeight: lineHeights.sm, }, lg: { fontSize: fontSizes.md, lineHeight: lineHeights.md, },})
const paginationIcon = stylex.create({ base: { width: '1.15em', height: '1.15em', flexShrink: 0, },})
export type PaginationVariant = keyof typeof paginationItemVariants
export type PaginationSize = keyof typeof paginationItemSizes
const paginationSlotRecipe = defineSlotRecipe({ slots: { root: { styles: paginationRoot }, item: { styles: paginationItem, sizes: paginationItemSizes, variants: paginationItemVariants, }, ellipsis: { styles: paginationEllipsis, sizes: paginationEllipsisSizes }, text: { styles: paginationText, sizes: paginationTextSizes }, }, defaultVariants: { variant: "outline", size: "md" },});
const { withProvider, withContext } = createSlotRecipeContext(paginationSlotRecipe);
type PaginationVariants = SlotRecipeVariants<typeof paginationSlotRecipe>;
function ChevronLeftIcon() { return ( <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(paginationIcon.base)}> <path d="m10 4-4 4 4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
function ChevronRightIcon() { return ( <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(paginationIcon.base)}> <path d="m6 4 4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
function ChevronsLeftIcon() { return ( <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(paginationIcon.base)}> <path d="m8 4-4 4 4 4M12.5 4l-4 4 4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
function ChevronsRightIcon() { return ( <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" {...stylex.props(paginationIcon.base)}> <path d="m3.5 4 4 4-4 4M8 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /> </svg> );}
// --- page range -------------------------------------------------------------// Base UI has no pagination primitive. The range logic mirrors Ark/Zag's so// both engines show the same pages: always `boundaryCount` pages at each// edge, `siblingCount` pages around the current one, and an ellipsis for// each collapsed gap (a gap of exactly one page shows that page instead).
export type PageEntry = { type: "page"; value: number } | { type: "ellipsis" };
const range = (start: number, end: number) => Array.from({ length: Math.max(end - start + 1, 0) }, (_, i) => start + i);
function getPages( page: number, totalPages: number, siblingCount: number, boundaryCount: number,): PageEntry[] { if (totalPages <= 0) return []; const first = 1; const last = totalPages; const left = Math.max(page - siblingCount, first); const right = Math.min(page + siblingCount, last); const slots = Math.min(siblingCount * 2 + 3 + boundaryCount * 2, totalPages); let pages: (number | "ellipsis")[]; if (totalPages <= slots) { pages = range(first, last); } else { const itemCount = slots - 1 - boundaryCount; const leftGap = left > first + boundaryCount + 1; const rightGap = right < last - boundaryCount - 1; if (!leftGap && rightGap) { pages = [...range(1, itemCount), "ellipsis", ...range(last - boundaryCount + 1, last)]; } else if (leftGap && !rightGap) { pages = [ ...range(first, first + boundaryCount - 1), "ellipsis", ...range(last - itemCount + 1, last), ]; } else if (leftGap && rightGap) { pages = [ ...range(first, first + boundaryCount - 1), "ellipsis", ...range(left, right), "ellipsis", ...range(last - boundaryCount + 1, last), ]; } else { pages = range(first, last); } } // an ellipsis hiding a single page is replaced by that page pages = pages.map((entry, i) => { if (entry !== "ellipsis") return entry; const prev = typeof pages[i - 1] === "number" ? (pages[i - 1] as number) : 0; const next = typeof pages[i + 1] === "number" ? (pages[i + 1] as number) : totalPages + 1; return next - prev === 2 ? prev + 1 : entry; }); return pages.map((entry) => entry === "ellipsis" ? { type: "ellipsis" } : { type: "page", value: entry }, );}
// --- state --------------------------------------------------------------------
export interface PaginationApi { count: number; page: number; pageSize: number; totalPages: number; /** The visible page range, with ellipsis entries for collapsed gaps. */ pages: PageEntry[]; previousPage: number | null; nextPage: number | null; /** Slice bounds of the current page in a `count`-long list. */ pageRange: { start: number; end: number }; type: "button" | "link"; slice: <T>(data: T[]) => T[]; getPageUrl: (page: number) => string | undefined; setPage: (page: number) => void; setPageSize: (size: number) => void; goToNextPage: () => void; goToPrevPage: () => void; goToFirstPage: () => void; goToLastPage: () => void;}
const PaginationContext = createContext<PaginationApi | null>(null);
function usePagination() { const ctx = useContext(PaginationContext); if (!ctx) throw new Error("Pagination parts must be rendered inside <Pagination.Root>"); return ctx;}
interface PaginationOwnProps { /** Total number of data items. */ count: number; /** Controlled current page (1-based). */ page?: number; /** @default 1 */ defaultPage?: number; onPageChange?: (details: { page: number; pageSize: number }) => void; /** Controlled number of data items per page. */ pageSize?: number; /** @default 10 */ defaultPageSize?: number; onPageSizeChange?: (details: { pageSize: number }) => void; /** Pages shown on each side of the current page. @default 1 */ siblingCount?: number; /** Pages always shown at each edge. @default 1 */ boundaryCount?: number; /** Render pages as buttons (default) or as links built by `getPageUrl`. */ type?: "button" | "link"; getPageUrl?: (details: { page: number; pageSize: number }) => string;}
const clampPage = (page: number, total: number) => Math.min(Math.max(page, 1), Math.max(total, 1));
function RootNode({ render, count, page: pageProp, defaultPage = 1, onPageChange, pageSize: pageSizeProp, defaultPageSize = 10, onPageSizeChange, siblingCount = 1, boundaryCount = 1, type = "button", getPageUrl, ...rest}: useRender.ComponentProps<"nav"> & PaginationOwnProps) { const [innerPage, setInnerPage] = useState(defaultPage); const [innerPageSize, setInnerPageSize] = useState(defaultPageSize); const pageSize = pageSizeProp ?? innerPageSize; const totalPages = Math.ceil(count / pageSize); const page = pageProp ?? innerPage;
const api = useMemo<PaginationApi>(() => { const setPage = (next: number) => { const clamped = clampPage(next, totalPages); if (clamped === page) return; setInnerPage(clamped); onPageChange?.({ page: clamped, pageSize }); }; const start = (page - 1) * pageSize; return { count, page, pageSize, totalPages, pages: getPages(page, totalPages, siblingCount, boundaryCount), previousPage: page > 1 ? page - 1 : null, nextPage: page < totalPages ? page + 1 : null, pageRange: { start, end: Math.min(start + pageSize, count) }, type, slice: (data) => data.slice(start, start + pageSize), getPageUrl: (p) => getPageUrl?.({ page: p, pageSize }), setPage, setPageSize: (size) => { setInnerPageSize(size); onPageSizeChange?.({ pageSize: size }); // keep the page valid for the new size const nextTotal = Math.ceil(count / size); if (page > nextTotal) setPage(Math.max(nextTotal, 1)); }, goToNextPage: () => setPage(page + 1), goToPrevPage: () => setPage(page - 1), goToFirstPage: () => setPage(1), goToLastPage: () => setPage(totalPages), }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [count, page, pageSize, totalPages, siblingCount, boundaryCount, type, getPageUrl]);
const element = useRender({ defaultTagName: "nav", render: render as useRender.RenderProp, props: mergeProps<"nav">({ "aria-label": "pagination" }, rest), }); return <PaginationContext.Provider value={api}>{element}</PaginationContext.Provider>;}
/** * Pagination — a hand-built pagination for Base UI (which ships no * pagination primitive) composed through `useRender` / `mergeProps` and * wearing the pagination recipe. `<Pagination.Root count pageSize * siblingCount variant size>` renders a labelled `<nav>` and owns the page * state; items carry `aria-current="page"` / `data-selected` and triggers * disable at the edges. `variant` picks the current-page treatment (solid, * subtle, outline). `Pagination.Items` renders the page range; or map it * yourself through `Pagination.Context`. Composition per part via `render`. */export type PaginationRootProps = WithStyleOverrides<useRender.ComponentProps<"nav">> & PaginationOwnProps & Partial<PaginationVariants>;
const PaginationRoot = withProvider(RootNode, "root", "PaginationRoot");
function Root(props: PaginationRootProps) { return <PaginationRoot {...(props as React.ComponentProps<typeof PaginationRoot>)} />;}Root.displayName = "PaginationRoot";
// --- parts --------------------------------------------------------------------
type ButtonOrLinkProps = useRender.ComponentProps<"button"> & Omit<React.ComponentProps<"a">, keyof React.ComponentProps<"button">>;
/** A page button (or link when Root has `type="link"`). */function PageButton({ render, pageTarget, disabled, label, onPick, extra, ...rest}: ButtonOrLinkProps & { pageTarget: number | null; disabled: boolean; label: string; onPick: () => void; extra?: Record<string, unknown>;}) { const api = usePagination(); const isLink = api.type === "link"; const href = !disabled && pageTarget != null ? api.getPageUrl(pageTarget) : undefined; const own: Record<string, unknown> = { "aria-label": label, "data-disabled": disabled ? "" : undefined, onClick: () => { if (!disabled) onPick(); }, ...extra, }; if (isLink) { if (disabled || href == null) { own.role = "link"; own["aria-disabled"] = disabled ? true : undefined; } else { own.href = href; } } else { own.type = "button"; own.disabled = disabled; } return useRender({ defaultTagName: isLink ? "a" : "button", render: render as useRender.RenderProp, props: mergeProps(own, rest as Record<string, unknown>), });}
export type PaginationItemProps = Omit<ButtonOrLinkProps, "type"> & { /** The page this item selects. */ value: number; /** Kept for parity with the Ark UI API; only `"page"` is valid. */ type?: "page";};
function ItemNode({ value, type: _type, children, ...rest }: PaginationItemProps) { const api = usePagination(); const selected = value === api.page; return ( <PageButton pageTarget={value} disabled={false} label={`${api.totalPages > 1 && value === api.totalPages ? "last page, " : ""}page ${value}`} onPick={() => api.setPage(value)} extra={{ "data-index": value, "data-selected": selected ? "" : undefined, "aria-current": selected ? "page" : undefined, }} {...rest} > {children ?? value} </PageButton> );}
function EllipsisNode({ render, index: _index, children, ...rest}: useRender.ComponentProps<"div"> & { index?: number }) { return useRender({ defaultTagName: "div", render: render as useRender.RenderProp, props: mergeProps<"div">({ children: children ?? "…" }, rest), });}
type TriggerKind = "prev" | "next" | "first" | "last";
const triggerConfig: Record< TriggerKind, { label: string; icon: () => React.ReactElement }> = { prev: { label: "previous page", icon: ChevronLeftIcon }, next: { label: "next page", icon: ChevronRightIcon }, first: { label: "first page", icon: ChevronsLeftIcon }, last: { label: "last page", icon: ChevronsRightIcon },};
function makeTrigger(kind: TriggerKind) { function TriggerNode({ children, ...rest }: ButtonOrLinkProps) { const api = usePagination(); const atStart = api.page <= 1; const atEnd = api.page >= api.totalPages; const target = kind === "prev" ? api.previousPage : kind === "next" ? api.nextPage : kind === "first" ? 1 : api.totalPages; const disabled = kind === "prev" || kind === "first" ? atStart : atEnd; const Icon = triggerConfig[kind].icon; return ( <PageButton pageTarget={target} disabled={disabled} label={triggerConfig[kind].label} onPick={() => target != null && api.setPage(target)} {...rest} > {children ?? <Icon />} </PageButton> ); } return TriggerNode;}
const Item = withContext(ItemNode, "item", "PaginationItem");const Ellipsis = withContext(EllipsisNode, "ellipsis", "PaginationEllipsis");
/** * Items — the page range (`pagination.pages`): one Item per page and an * Ellipsis for every collapsed gap. */function Items(props: StyleOverrideProps) { const api = usePagination(); return ( <> {api.pages.map((page, index) => page.type === "page" ? ( <Item key={page.value} type="page" value={page.value} {...props} /> ) : ( <Ellipsis key={`ellipsis-${index}`} index={index} {...props} /> ), )} </> );}Items.displayName = "PaginationItems";
/** Render-prop access to the pagination state, like Ark's `Pagination.Context`. */function Context({ children }: { children: (pagination: PaginationApi) => React.ReactNode }) { return <>{children(usePagination())}</>;}
export const Pagination = { Root, Items, Item, Ellipsis, PrevTrigger: withContext(makeTrigger("prev"), "item", "PaginationPrevTrigger"), NextTrigger: withContext(makeTrigger("next"), "item", "PaginationNextTrigger"), FirstTrigger: withContext(makeTrigger("first"), "item", "PaginationFirstTrigger"), LastTrigger: withContext(makeTrigger("last"), "item", "PaginationLastTrigger"), /** Muted inline text for summaries such as "Page 3 of 12". */ Text: withContext("span", "text", "PaginationText"), Context,};
export { usePagination };