---
title: "Pagination · UI SDK — StyleX Blocks"
description: "Page navigation with prev/next triggers, sibling and boundary pages, and ellipses for long ranges."
url: "https://stylexblocks.com/components/ui-sdk/pagination/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Pagination

Page navigation with prev/next triggers, sibling and boundary pages, and ellipses for long ranges.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/pagination.md), [Base UI](https://stylexblocks.com/components/base-ui/pagination.md)
- Category: Display
- Variants: outline, subtle, solid
- Sizes: xs, sm, md, lg
- Used in blocks: [Searchable Table](https://stylexblocks.com/block/ui-sdk/searchable-table.md), [Simple Table](https://stylexblocks.com/block/ui-sdk/simple-table.md)
- HTML page: https://stylexblocks.com/components/ui-sdk/pagination/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add pagination
```

Equivalent: `npx shadcn add @stylexblocks/pagination`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/pagination.json

## Usage

```tsx
import { Pagination } from "#components/ui/ui-sdk/pagination.tsx";
import { indigoPalette } from "@stylexblocks/ui/themes/palettes.ts";

export function Example() {
  return (
    // UI SDK's pagination behind the same Root props: the engine renders
    // a labelled <nav> with the pages in a list, computes the range, marks
    // aria-current="page", and keeps the end steps focusable with
    // aria-disabled. type="link" + getPageUrl renders real anchors.
    <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)}>
```

## Examples

### Compact with page text

Read the state through Pagination.Context to show “Page 3 of 12” between first/prev and next/last triggers.

```tsx
import { Pagination } from "#components/ui/ui-sdk/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.

```tsx
import { useState } from "react";
import { Pagination } from "#components/ui/ui-sdk/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>
    </>
  );
}
```

## Source

`components/ui/ui-sdk/pagination.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useMemo, useState } from "react";
import {
  Pagination as UiSdkPagination,
  PaginationEllipsis,
  PaginationFirst,
  PaginationItem,
  PaginationLast,
  PaginationLink,
  PaginationList,
  PaginationNext,
  PaginationPrevious,
  paginationRange,
} from "@ui-sdk/react/pagination";
import type { PartProps } from "@ui-sdk/react/primitive";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  type SlotRecipeVariants,
  type StyleOverrideProps,
} 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" },
});

// UI SDK wants the pages in a list (`<ul>` of `<li>`): the list and items
// drop out of the layout so the recipe's flex row on the root `<nav>` lays
// out the buttons directly.
const chrome = stylex.create({
  list: {
    display: "contents",
    listStyle: "none",
    margin: 0,
    padding: 0,
  },
  listItem: {
    display: "contents",
  },
});

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>
  );
}

// --- state --------------------------------------------------------------------

export type PageEntry = { type: "page"; value: number } | { type: "ellipsis" };

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;
  /** Every page and step does nothing, like a step at its end. */
  disabled?: boolean;
}

const clampPage = (page: number, total: number) => Math.min(Math.max(page, 1), Math.max(total, 1));

function RootNode({
  count,
  page: pageProp,
  defaultPage = 1,
  onPageChange,
  pageSize: pageSizeProp,
  defaultPageSize = 10,
  onPageSizeChange,
  siblingCount = 1,
  boundaryCount = 1,
  type = "button",
  getPageUrl,
  disabled,
  children,
  ...rest
}: Omit<PartProps<"nav">, "onChange"> & PaginationOwnProps) {
  const [innerPage, setInnerPage] = useState(defaultPage);
  const [innerPageSize, setInnerPageSize] = useState(defaultPageSize);
  const pageSize = pageSizeProp ?? innerPageSize;
  const totalPages = Math.max(Math.ceil(count / pageSize), 1);
  const page = clampPage(pageProp ?? innerPage, totalPages);

  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;
    const range = paginationRange({
      page,
      pageCount: totalPages,
      siblings: siblingCount,
      boundaries: boundaryCount,
    });
    return {
      count,
      page,
      pageSize,
      totalPages,
      pages: range.map((entry) =>
        typeof entry === "number" ? { type: "page", value: entry } : { type: "ellipsis" },
      ),
      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]);

  return (
    <PaginationContext.Provider value={api}>
      <UiSdkPagination
        aria-label="pagination"
        {...rest}
        page={page}
        pageCount={totalPages}
        siblings={siblingCount}
        boundaries={boundaryCount}
        disabled={disabled}
        getHref={type === "link" && getPageUrl ? (p) => getPageUrl({ page: p, pageSize }) : undefined}
        onPageChange={(next) => api.setPage(next)}
      >
        <PaginationList {...stylex.props(chrome.list)}>{children}</PaginationList>
      </UiSdkPagination>
    </PaginationContext.Provider>
  );
}

/**
 * Pagination — UI SDK's pagination wearing the pagination recipe, behind
 * the same Root props as the other engines. `<Pagination.Root count
 * pageSize siblingCount variant size>` owns the page state and hands it to
 * the engine, which renders a labelled `<nav>` with the pages in a list,
 * computes the range (`paginationRange`), marks the current page
 * `aria-current="page"` / `data-current`, and keeps the steps at either end
 * focusable with `aria-disabled`. `type="link"` + `getPageUrl` renders real
 * anchors. `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 = Omit<PartProps<"nav">, "onChange" | "style"> &
  StyleOverrideProps &
  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 --------------------------------------------------------------------

// Every page, step and text sits in its own list item.
function ListItem({ children }: { children: React.ReactNode }) {
  return <PaginationItem {...stylex.props(chrome.listItem)}>{children}</PaginationItem>;
}

export type PaginationItemProps = Omit<PartProps<"a">, "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();
  return (
    <ListItem>
      <PaginationLink
        page={value}
        aria-label={`${api.totalPages > 1 && value === api.totalPages ? "last page, " : ""}page ${value}`}
        {...rest}
      >
        {children ?? value}
      </PaginationLink>
    </ListItem>
  );
}

function EllipsisNode({
  index: _index,
  children,
  ...rest
}: PartProps<"span"> & { index?: number }) {
  return (
    <ListItem>
      <PaginationEllipsis {...rest}>{children ?? "…"}</PaginationEllipsis>
    </ListItem>
  );
}

type TriggerKind = "prev" | "next" | "first" | "last";

const triggerConfig: Record<
  TriggerKind,
  {
    label: string;
    icon: () => React.ReactElement;
    Step: typeof PaginationPrevious;
  }
> = {
  prev: { label: "previous page", icon: ChevronLeftIcon, Step: PaginationPrevious },
  next: { label: "next page", icon: ChevronRightIcon, Step: PaginationNext },
  first: { label: "first page", icon: ChevronsLeftIcon, Step: PaginationFirst },
  last: { label: "last page", icon: ChevronsRightIcon, Step: PaginationLast },
};

function makeTrigger(kind: TriggerKind) {
  function TriggerNode({ children, ...rest }: React.ComponentProps<typeof PaginationPrevious>) {
    const { label, icon: Icon, Step } = triggerConfig[kind];
    return (
      <ListItem>
        <Step aria-label={label} {...rest}>
          {children ?? <Icon />}
        </Step>
      </ListItem>
    );
  }
  return TriggerNode;
}

function TextNode(props: React.ComponentProps<"span">) {
  return (
    <ListItem>
      <span {...props} />
    </ListItem>
  );
}

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(TextNode, "text", "PaginationText"),
  Context,
};

export { usePagination };
```
