Skip to content
Atoms

Pagination

Pages with a marker that slides to the pick.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add pagination

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/pagination.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/pagination and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { Pagination } from "asta-ui/pagination";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useLayoutEffect, useRef, useState } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface PaginationProps {
      /** Total number of pages. */
      count: number;
      /** Current page, 1-based. */
      page?: number;
      defaultPage?: number;
      onPageChange?: (page: number) => void;
      /** Pages shown on each side of the current one. */
      siblings?: number;
      /** Pages always shown at the start and end. */
      boundaries?: number;
      size?: "sm" | "md";
      /** Accessible name, e.g. "Orders pages". */
      label?: string;
      className?: string;
    }
    
    type Slot = number | "start-gap" | "end-gap";
    
    /** The page numbers to show, with gaps where pages are skipped. A gap never hides just one page. */
    export function pageRange(page: number, count: number, siblings = 1, boundaries = 1): Slot[] {
      const total = boundaries * 2 + siblings * 2 + 3;
      const range = (a: number, b: number) => Array.from({ length: Math.max(0, b - a + 1) }, (_, i) => a + i);
      if (count <= total) return range(1, count);
      const left = Math.max(page - siblings, boundaries + 2);
      const right = Math.min(page + siblings, count - boundaries - 1);
      const showStart = left > boundaries + 2;
      const showEnd = right < count - boundaries - 1;
      const head = range(1, boundaries);
      const tail = range(count - boundaries + 1, count);
      if (!showStart) return [...range(1, total - boundaries - 1), "end-gap", ...tail];
      if (!showEnd) return [...head, "start-gap", ...range(count - (total - boundaries - 2), count)];
      return [...head, "start-gap", ...range(left, right), "end-gap", ...tail];
    }
    
    const Arrow = ({ dir }: { dir: -1 | 1 }) => (
      <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
        <path d={dir === 1 ? "M9.5 6l6 6-6 6" : "M14.5 6l-6 6 6 6"} />
      </svg>
    );
    
    /**
     * Page numbers with previous and next. Skipped pages collapse into an ellipsis, and the active marker slides
     * from the old page to the new one. Arrow keys move a page while focus is inside.
     */
    export function Pagination({ count, page, defaultPage = 1, onPageChange, siblings = 1, boundaries = 1, size = "md", label = "Pagination", className }: PaginationProps) {
      const [inner, setInner] = useState(defaultPage);
      const pages = Math.max(1, count);
      const current = Math.min(pages, Math.max(1, page ?? inner));
      const list = useRef<HTMLUListElement>(null);
      const marker = useRef<HTMLSpanElement>(null);
      const placed = useRef(false);
    
      const go = (n: number) => {
        const next = Math.min(pages, Math.max(1, n));
        if (next === current) return;
        if (page === undefined) setInner(next);
        onPageChange?.(next);
      };
    
      const slots = pageRange(current, pages, siblings, boundaries);
    
      // Move the marker under the active button. Page changes slide it, resizes and the first placement snap.
      const place = (animate: boolean) => {
        const btn = list.current?.querySelector<HTMLElement>("[aria-current=page]");
        const m = marker.current;
        if (!btn || !m) return;
        m.style.transition = animate && placed.current ? "" : "none";
        m.style.width = `${btn.offsetWidth}px`;
        m.style.transform = `translateX(${btn.offsetLeft}px)`;
        m.style.opacity = "1";
        placed.current = true;
      };
      const placeRef = useRef(place);
      useLayoutEffect(() => {
        placeRef.current = place;
        place(true);
      });
      useLayoutEffect(() => {
        let first = true;
        const ro = new ResizeObserver(() => {
          if (first) first = false;
          else placeRef.current(false);
        });
        if (list.current) ro.observe(list.current);
        return () => ro.disconnect();
      }, []);
    
      const h = size === "md" ? "h-9 min-w-9 text-[13.5px]" : "h-8 min-w-8 text-[13px]";
      const btn = cx("relative flex items-center justify-center rounded-lg px-2 tabular-nums outline-none transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-brand/50", h);
    
      return (
        <nav
          aria-label={label}
          className={cx("flex items-center gap-1", className)}
          onKeyDown={(e) => {
            if (e.key === "ArrowLeft") go(current - 1);
            else if (e.key === "ArrowRight") go(current + 1);
            else return;
            e.preventDefault();
            // Keep focus on the active page after the move.
            requestAnimationFrame(() => list.current?.querySelector<HTMLElement>("[aria-current=page]")?.focus());
          }}
        >
          <button type="button" onClick={() => go(current - 1)} disabled={current === 1} aria-label="Previous page" className={cx(btn, "text-ink-2 hover:bg-paper-2 hover:text-ink disabled:pointer-events-none disabled:opacity-35")}>
            <Arrow dir={-1} />
          </button>
          <div className="relative">
            <span
              ref={marker}
              aria-hidden
              className={cx("pointer-events-none absolute left-0 top-0 rounded-lg bg-[color-mix(in_srgb,var(--color-brand)_11%,transparent)] opacity-0 transition-transform duration-[420ms] ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:!transition-none", size === "md" ? "h-9" : "h-8")}
            />
            <ul ref={list} className="flex items-center gap-1">
            {slots.map((s) =>
              typeof s === "number" ? (
                <li key={s}>
                  <button
                    type="button"
                    onClick={() => go(s)}
                    aria-current={s === current ? "page" : undefined}
                    aria-label={`Page ${s}`}
                    className={cx(btn, s === current ? "font-medium text-brand" : "text-ink-2 hover:bg-paper-2 hover:text-ink")}
                  >
                    {s}
                  </button>
                </li>
              ) : (
                <li key={s} aria-hidden className={cx("flex items-center justify-center text-mute", h)}>
                  …
                </li>
              ),
            )}
            </ul>
          </div>
          <button type="button" onClick={() => go(current + 1)} disabled={current === pages} aria-label="Next page" className={cx(btn, "text-ink-2 hover:bg-paper-2 hover:text-ink disabled:pointer-events-none disabled:opacity-35")}>
            <Arrow dir={1} />
          </button>
        </nav>
      );
    }
    
    export default Pagination;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Pagination component to my project.
    
    Pages with a marker that slides to the pick.
    It includes: prev/next, ellipsis, siblings, boundaries, sliding marker, keys.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add pagination --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/pagination.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Pagination } from "@/components/astabyte/pagination";
    ```
    
    Usage example and props: https://ui.astabyte.com/pagination
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Links point at ?page=N: the server renders the page range and aria-current. -->
    <div style="display:grid;gap:12px">
    <nav class="asta-pagination" aria-label="Pagination"><a class="asta-pagination-link" href="?page=4" aria-label="Previous page"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3.5 5.5 8l4.5 4.5"/></svg></a><ul class="asta-pagination-list"><li><a class="asta-pagination-link" href="?page=1" aria-label="Page 1">1</a></li><li class="asta-pagination-gap" aria-hidden="true">…</li><li><a class="asta-pagination-link" href="?page=4" aria-label="Page 4">4</a></li><li><a class="asta-pagination-link" href="?page=5" aria-current="page" aria-label="Page 5">5</a></li><li><a class="asta-pagination-link" href="?page=6" aria-label="Page 6">6</a></li><li class="asta-pagination-gap" aria-hidden="true">…</li><li><a class="asta-pagination-link" href="?page=12" aria-label="Page 12">12</a></li></ul><a class="asta-pagination-link" href="?page=6" aria-label="Next page"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 3.5 4.5 4.5L6 12.5"/></svg></a></nav><nav class="asta-pagination asta-pagination-sm" aria-label="Pagination"><span role="link" aria-disabled="true" aria-label="Previous page" class="asta-pagination-link"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 3.5 5.5 8l4.5 4.5"/></svg></span><ul class="asta-pagination-list"><li><a class="asta-pagination-link" href="?page=1" aria-current="page" aria-label="Page 1">1</a></li><li><a class="asta-pagination-link" href="?page=2" aria-label="Page 2">2</a></li><li><a class="asta-pagination-link" href="?page=3" aria-label="Page 3">3</a></li></ul><a class="asta-pagination-link" href="?page=2" aria-label="Next page"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 3.5 4.5 4.5L6 12.5"/></svg></a></nav>
    </div>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { Pagination } from "@/components/astabyte/pagination";

const TOTAL = 248;
const PER_PAGE = 10;

export default function PaginationDemo() {
  const [page, setPage] = useState(5);
  const from = (page - 1) * PER_PAGE + 1;
  const to = Math.min(TOTAL, page * PER_PAGE);

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-lg flex-col items-center gap-10">
        <div className="flex w-full flex-col items-center gap-4 rounded-xl bg-paper-2 px-4 py-5">
          <p className="text-[13px] tabular-nums text-mute">
            Showing <span className="text-ink">{from}–{to}</span> of {TOTAL} orders
          </p>
          <Pagination label="Orders pages" count={Math.ceil(TOTAL / PER_PAGE)} page={page} onPageChange={setPage} />
        </div>
        <Pagination label="Results pages" count={6} size="sm" />
        <p className="text-center text-[12.5px] text-mute">Click a page or use the arrow keys once a page has focus.</p>
      </div>
    </div>
  );
}