Menu

Components

Pagination

Buttons to move between the pages of a long list, with the page numbers and a … where the middle is left out.

Introduction

Pagination splits a long list, a table or search results into pages, and lets people move between them. It shows where you are, offers the next and previous page, and keeps the row short with a … however many pages there are.

  • The row keeps the same length while you page, so the buttons do not move under the pointer.
  • The current page is filled in and marked aria-current="page". Previous and next disable at the ends.
  • Uncontrolled by default. Control it with page and onPageChange.
  • With hrefBuilder every button becomes a real link, so each page has a URL to share and search engines can follow.
  • Add first and last buttons, swap the numbers for "Page 3 of 12" in tight places, or make the buttons fully round with isCircle.

Pagination does not fetch or slice anything. It gives you the page number, and you show that page of your data.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Pagination is made of Buttons.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Add Button first (see its Manual installation), then follow the steps below.

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the hook and the styles

src/types/use-pagination.tsShow code
import { useState } from "react";

export type PaginationItem = number | "ellipsis-start" | "ellipsis-end";

const range = (from: number, to: number) =>
  Array.from({ length: Math.max(to - from + 1, 0) }, (_, i) => from + i);

/**
 * The page numbers to show, with "…" where pages are left out. It keeps the
 * `boundaries` first and last pages and the `siblings` around the current one,
 * and always returns the same number of items once there are enough pages, so
 * the row does not jump around while paging.
 *
 * getPaginationRange(10, 5) // [1, "ellipsis-start", 4, 5, 6, "ellipsis-end", 10]
 */
export function getPaginationRange(
  total: number,
  page: number,
  siblings = 1,
  boundaries = 1,
): PaginationItem[] {
  // Every page fits: two "…", the boundaries, the siblings and the current one.
  const fits = siblings * 2 + 3 + boundaries * 2;
  if (fits >= total) return range(1, total);

  const left = Math.max(page - siblings, boundaries + 1);
  const right = Math.min(page + siblings, total - boundaries);
  const hasLeftGap = left > boundaries + 2;
  const hasRightGap = right < total - boundaries - 1;

  if (!hasLeftGap && hasRightGap) {
    return [
      ...range(1, siblings * 2 + boundaries + 2),
      "ellipsis-end",
      ...range(total - boundaries + 1, total),
    ];
  }
  if (hasLeftGap && !hasRightGap) {
    return [
      ...range(1, boundaries),
      "ellipsis-start",
      ...range(total - (siblings * 2 + boundaries + 2) + 1, total),
    ];
  }
  return [
    ...range(1, boundaries),
    "ellipsis-start",
    ...range(left, right),
    "ellipsis-end",
    ...range(total - boundaries + 1, total),
  ];
}

export interface UsePaginationOptions {
  /** How many pages there are. */
  total: number;
  /** The current page (1-based), for a controlled pagination. */
  page?: number;
  /** The page to start on, for an uncontrolled one. Defaults to 1. */
  defaultPage?: number;
  onChange?: (page: number) => void;
  siblings?: number;
  boundaries?: number;
}

const clamp = (value: number, min: number, max: number) =>
  Math.min(Math.max(value, min), max);

/** The state and the page list of a pagination. Pagination is built on it. */
export function usePagination({
  total,
  page,
  defaultPage = 1,
  onChange,
  siblings = 1,
  boundaries = 1,
}: UsePaginationOptions) {
  const last = Math.max(total, 1);
  const [inner, setInner] = useState(defaultPage);
  const current = clamp(page ?? inner, 1, last);

  const setPage = (next: number) => {
    const target = clamp(next, 1, last);
    if (page === undefined) setInner(target);
    if (target !== current) onChange?.(target);
  };

  return {
    page: current,
    total: last,
    items: getPaginationRange(last, current, siblings, boundaries),
    setPage,
    isFirst: current === 1,
    isLast: current === last,
  };
}
src/types/pagination-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Pagination. The buttons are Buttons; these are the row, the "…"
// and the "Page 2 of 10" text.
export const paginationStyles = tv({
  slots: {
    list: "flex flex-wrap items-center gap-1",
    ellipsis: "flex items-center justify-center text-muted-fg select-none",
    summary: "px-3 text-muted-fg tabular-nums whitespace-nowrap",
    control: "",
    page: "",
  },
  variants: {
    size: {
      sm: { ellipsis: "size-8", summary: "text-xs", page: "min-w-8 px-2" },
      md: { ellipsis: "size-9", summary: "text-sm", page: "min-w-9 px-2" },
      lg: { ellipsis: "size-11", summary: "text-base", page: "min-w-11 px-3" },
    },
    // Round buttons. A page number stays a circle up to three digits and
    // becomes a pill when it needs the room.
    isCircle: {
      true: { control: "rounded-full", page: "px-0" },
      false: {},
    },
  },
  defaultVariants: { size: "md", isCircle: false },
});

2. Add the Pagination file

src/components/ui/pagination/pagination.tsxShow code
"use client";

import type NextLink from "next/link";
import type { ComponentProps, ReactNode } from "react";
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  ChevronsLeftIcon,
  ChevronsRightIcon,
  EllipsisIcon,
} from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { paginationStyles } from "@/types/pagination-styles";
import { usePagination } from "@/types/use-pagination";

type Href = ComponentProps<typeof NextLink>["href"];

export interface PaginationProps {
  /** How many pages there are. */
  total: number;
  /** The current page, starting at 1, for a controlled pagination. */
  page?: number;
  /** The page to start on, for an uncontrolled pagination. Defaults to 1. */
  defaultPage?: number;
  /** Called with the new page when the user picks one. */
  onPageChange?: (page: number) => void;
  /** Pages shown on each side of the current one. Defaults to 1. */
  siblings?: number;
  /** Pages always shown at the start and at the end. Defaults to 1. */
  boundaries?: number;
  /** Add buttons for the first and the last page. */
  showEdges?: boolean;
  /** Replace the page numbers with "Page 3 of 12", for narrow places. */
  isCompact?: boolean;
  /**
   * Make every button a link to this address, so each page has a URL that can
   * be shared, indexed and opened in a new tab. Pass the page from the URL as
   * `page`.
   */
  hrefBuilder?: (page: number) => Href;
  /** Make the buttons fully round instead of rounded squares. */
  isCircle?: boolean;
  /** Look of the pages that are not the current one. */
  variant?: "outline" | "ghost" | "secondary";
  size?: "sm" | "md" | "lg";
  isDisabled?: boolean;
  /** Names the navigation for screen readers. Defaults to "Pagination". */
  "aria-label"?: string;
  className?: string;
}

/**
 * Moves between the pages of a long list: previous and next buttons, and the
 * page numbers between them, with "…" where the middle is left out. The
 * current page is filled in and marked `aria-current="page"`.
 *
 * Uncontrolled by default. Control it with `page` and `onPageChange`, or give
 * it `hrefBuilder` to make every page a real link, for pages that live at a
 * URL. The page list comes from `usePagination`, which you can use on its own
 * for a different look.
 *
 * @example
 * <Pagination total={20} onPageChange={(page) => load(page)} />
 */
export function Pagination({
  total,
  page,
  defaultPage,
  onPageChange,
  siblings,
  boundaries,
  showEdges = false,
  isCompact = false,
  hrefBuilder,
  isCircle = false,
  variant = "outline",
  size = "md",
  isDisabled = false,
  className,
  ...props
}: PaginationProps) {
  const styles = paginationStyles({ size, isCircle });
  const state = usePagination({
    total,
    page,
    defaultPage,
    onChange: onPageChange,
    siblings,
    boundaries,
  });

  // A control to a page: a link when there is an hrefBuilder, else a button.
  // Past the ends, or when everything is disabled, it is a disabled button.
  function control(
    target: number,
    label: string,
    content: ReactNode,
    options: { isIcon: boolean; isCurrent?: boolean; isOff?: boolean },
  ) {
    const common = {
      size,
      variant: options.isCurrent ? ("primary" as const) : variant,
      isIcon: options.isIcon,
      "aria-label": label,
      "aria-current": options.isCurrent ? ("page" as const) : undefined,
      className: options.isIcon
        ? styles.control()
        : cn(styles.control(), styles.page()),
    };
    const off = isDisabled || options.isOff;

    if (hrefBuilder && !off) {
      return (
        <Button
          {...common}
          href={hrefBuilder(target)}
          onClick={() => onPageChange?.(target)}
        >
          {content}
        </Button>
      );
    }
    return (
      <Button
        {...common}
        isDisabled={off}
        onPress={() => state.setPage(target)}
      >
        {content}
      </Button>
    );
  }

  const prev = control(
    state.page - 1,
    "Go to previous page",
    <ChevronLeftIcon />,
    {
      isIcon: true,
      isOff: state.isFirst,
    },
  );
  const next = control(
    state.page + 1,
    "Go to next page",
    <ChevronRightIcon />,
    {
      isIcon: true,
      isOff: state.isLast,
    },
  );

  return (
    <nav aria-label={props["aria-label"] ?? "Pagination"} className={className}>
      <ul className={styles.list()}>
        {showEdges ? (
          <li>
            {control(1, "Go to first page", <ChevronsLeftIcon />, {
              isIcon: true,
              isOff: state.isFirst,
            })}
          </li>
        ) : null}
        <li>{prev}</li>
        {isCompact ? (
          <li className={styles.summary()}>
            Page {state.page} of {state.total}
          </li>
        ) : (
          state.items.map((item) =>
            typeof item === "number" ? (
              <li key={item}>
                {control(item, `Page ${item}`, item, {
                  isIcon: false,
                  isCurrent: item === state.page,
                })}
              </li>
            ) : (
              <li key={item} aria-hidden="true" className={styles.ellipsis()}>
                <EllipsisIcon className="size-4" />
              </li>
            ),
          )
        )}
        <li>{next}</li>
        {showEdges ? (
          <li>
            {control(state.total, "Go to last page", <ChevronsRightIcon />, {
              isIcon: true,
              isOff: state.isLast,
            })}
          </li>
        ) : null}
      </ul>
    </nav>
  );
}

It imports ChevronLeftIcon, ChevronRightIcon, ChevronsLeftIcon, ChevronsRightIcon and EllipsisIcon from @/components/icons. Add those icons, or swap them for your own.

3. Use it

import { Pagination } from "@/components/ui/pagination/pagination";

Anatomy

A navigation landmark with a list of controls: previous, the pages, next.

<Pagination total={20} defaultPage={8} showEdges />
PartRendered asNotes
Paginationnav with a ulA navigation landmark named "Pagination", holding a list of the controls.
First / lastButtonOptional, with showEdges. Jump to page 1 or the last page.
Previous / nextButtonDisabled on the first and the last page.
Page numberButton, or a linkOne per page shown. The current page is filled in and has aria-current="page".
Ellipsisspan, hidden from screen readersStands for the pages left out.

The page list

Which numbers show is decided by the current page, siblings (the pages beside it) and boundaries (the pages kept at each end). With the defaults, 1 each:

PagesCurrentShown
1011 2 3 4 5 … 10
1051 … 4 5 6 … 10
10101 … 6 7 8 9 10
531 2 3 4 5

Once there are more pages than fit, the row always has the same number of items, so it does not jump as you move. A … only ever stands for two pages or more: one page is shown instead.

Examples

Click a page, or use the arrows.

Usage

Controlled

Keep the page in your own state with page and onPageChange, to read it, load its data, or change it from elsewhere.

page: 3

Start page

defaultPage sets the page to start on. onPageChange still reports every change.

First and last

showEdges adds buttons that jump to the first and the last page, useful when there are many.

Siblings and boundaries

siblings sets how many pages show on each side of the current one, and boundaries how many stay at each end. With both at 0, only the current page shows, with a … on each side.

Compact

isCompact replaces the numbers with "Page 3 of 12". It fits a phone, a card or a table footer.

Few pages

When every page fits, they all show and there is no …. A single page has both arrows disabled.

Sizes

Variants

The variant is the look of the pages that are not current. The current one is always filled in.

Circle

isCircle makes every button fully round. It is a boolean: true for circles, false (the default) for rounded squares. A page number stays a circle up to three digits, and stretches into a pill only when it needs the room, such as page 12,000.

Disabled

With a list

Pagination only gives the page number. Here it slices a list of 42 orders, 5 to a page.

  • Order #1001
  • Order #1002
  • Order #1003
  • Order #1004
  • Order #1005

1–5 of 42

usePagination

The state and the page list are a hook, for a pagination that looks different. Pagination is built on it.

import { usePagination } from "@/types/use-pagination";

const { page, items, setPage, isFirst, isLast } = usePagination({
  total: 20,
  defaultPage: 5,
});

// items: [1, "ellipsis-start", 4, 5, 6, "ellipsis-end", 20]
OptionTypeDefault
totalnumber- (required)
pagenumber-
defaultPagenumber1
onChange(page: number) => void-
siblingsnumber1
boundariesnumber1

It returns page, total, items (the numbers and the two kinds of ellipsis), setPage, isFirst and isLast. The pure function getPaginationRange(total, page, siblings, boundaries) gives the list without any state.

Component API

Pagination takes the props below.

PropTypeDefault
totalnumber- (required)
pagenumber-
defaultPagenumber1
onPageChange(page: number) => void-
siblingsnumber1
boundariesnumber1
showEdgesbooleanfalse
isCompactbooleanfalse
isCirclebooleanfalse
hrefBuilder(page: number) => string | UrlObject-
variant"outline" | "ghost" | "secondary""outline"
size"sm" | "md" | "lg""md"
isDisabledbooleanfalse
aria-labelstring"Pagination"
classNamestring-