# Pagination

import * as React from "react";
import { Callout } from "fumadocs-ui/components/callout";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import { Step, Steps } from "fumadocs-ui/components/steps";
import { Tabs, Tab } from "fumadocs-ui/components/tabs";
import {
  Badge,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationPrevious,
  PaginationNext,
  PaginationEllipsis,
  buildPaginationRange,
} from "@pycolors/ui";
import {
  ArrowRight,
  CheckCircle,
  ChevronRight,
  Database,
  LayoutTemplate,
  LoaderCircle,
  Rows3,
  SearchX,
  Table2,
  XCircle,
} from "lucide-react";
import { PreferAvoid } from "@/components/docs/prefer-avoid";
import { DocsLinks } from "@/components/docs/docs-links";
import { DocsFeatureGrid } from "@/components/docs/docs-feature-grid";
import { DocsConceptTabs } from "@/components/docs/docs-concept-tabs";

import {
  PaginationBasicExample,
  ProjectsTableWithPagination,
} from "../previews/pagination-previews";

<div className="flex flex-wrap items-center gap-2">
  <Badge variant="outline">
    UI
  </Badge>

  <Badge>
    Pagination
  </Badge>
</div>

## Controlled navigation for paged content

The **Pagination** component provides composable UI primitives for navigating paged content.

Use it for:

* data tables
* admin lists
* reports
* invoices
* users
* projects
* search results
* paged dashboard views

Pagination is intentionally **dumb**. It does not own routing, fetching, URL sync, cursor logic, page-size logic, or server state.

The page or data layer owns the logic. The UI renders navigation.

<Callout title="Core idea">
  Pagination should render page navigation, not own the data model.
</Callout>

### Import

```tsx title="pagination-import.tsx"
import { Pagination } from "@pycolors/ui";
```

### Basic usage

Pagination is composed from small primitives:

* `Pagination` → wrapper navigation element
* `PaginationContent` → list container
* `PaginationItem` → item wrapper
* `PaginationLink` → page control
* `PaginationPrevious` / `PaginationNext` → directional controls
* `PaginationEllipsis` → compact overflow indicator

<Tabs items={["Preview", "Code"]}>
  <Tab value="Preview">
    <Preview>
      <PaginationBasicExample />
    </Preview>
  </Tab>

  <Tab value="Code">
    ```tsx title="pagination-basic-example.tsx"
    "use client";

    import * as React from "react";
    import {
      Pagination,
      PaginationContent,
      PaginationItem,
      PaginationLink,
      PaginationPrevious,
      PaginationNext,
      PaginationEllipsis,
      buildPaginationRange,
    } from "@pycolors/ui";

    export function PaginationBasicExample() {
      const [page, setPage] = React.useState(1);
      const totalPages = 12;

      const tokens = buildPaginationRange({ page, totalPages });

      return (
        <Pagination>
          <PaginationContent>
            <PaginationItem>
              <PaginationPrevious
                disabled={page === 1}
                onClick={() => setPage((current) => Math.max(1, current - 1))}
              />
            </PaginationItem>

            {tokens.map((token) =>
              token.type === "ellipsis" ? (
                <PaginationItem key={token.key}>
                  <PaginationEllipsis />
                </PaginationItem>
              ) : (
                <PaginationItem key={token.value}>
                  <PaginationLink
                    isActive={token.isActive}
                    onClick={() => setPage(token.value)}
                  >
                    {token.value}
                  </PaginationLink>
                </PaginationItem>
              ),
            )}

            <PaginationItem>
              <PaginationNext
                disabled={page === totalPages}
                onClick={() =>
                  setPage((current) => Math.min(totalPages, current + 1))
                }
              />
            </PaginationItem>
          </PaginationContent>
        </Pagination>
      );
    }
    ```
  </Tab>
</Tabs>

### Link composition

`PaginationLink`, `PaginationPrevious`, and `PaginationNext` support the
`asChild` composition pattern. Pass a real anchor (or a framework `Link`) as
the child and the control renders it as the root element while preserving all
styling, `data-slot`, accessible labels, and — for `PaginationPrevious` and
`PaginationNext` — the built-in icon and visible text.

<Tabs items={["Preview", "Code"]}>
  <Tab value="Preview">
    <Preview>
      <Pagination>
        <PaginationContent>
          <PaginationItem>
            <PaginationPrevious asChild>
              <a href="#previous" />
            </PaginationPrevious>
          </PaginationItem>

          <PaginationItem>
            <PaginationLink asChild>
              <a href="#page-1">
                1
              </a>
            </PaginationLink>
          </PaginationItem>

          <PaginationItem>
            <PaginationLink asChild isActive>
              <a href="#page-2">
                2
              </a>
            </PaginationLink>
          </PaginationItem>

          <PaginationItem>
            <PaginationLink asChild>
              <a href="#page-3">
                3
              </a>
            </PaginationLink>
          </PaginationItem>

          <PaginationItem>
            <PaginationEllipsis />
          </PaginationItem>

          <PaginationItem>
            <PaginationNext asChild>
              <a href="#next" />
            </PaginationNext>
          </PaginationItem>
        </PaginationContent>
      </Pagination>
    </Preview>
  </Tab>

  <Tab value="Code">
    ```tsx title="pagination-link-composition.tsx"
    import {
      Pagination,
      PaginationContent,
      PaginationItem,
      PaginationLink,
      PaginationPrevious,
      PaginationNext,
      PaginationEllipsis,
    } from "@pycolors/ui";

    // With real <a> elements — swap for your framework Link:
    <Pagination>
      <PaginationContent>
        <PaginationItem>
          <PaginationPrevious asChild>
            <a href="/page/1" />
          </PaginationPrevious>
        </PaginationItem>
        <PaginationItem>
          <PaginationLink asChild>
            <a href="/page/1">1</a>
          </PaginationLink>
        </PaginationItem>
        <PaginationItem>
          <PaginationLink asChild isActive>
            <a href="/page/2">2</a>
          </PaginationLink>
        </PaginationItem>
        <PaginationItem>
          <PaginationLink asChild>
            <a href="/page/3">3</a>
          </PaginationLink>
        </PaginationItem>
        <PaginationItem>
          <PaginationEllipsis />
        </PaginationItem>
        <PaginationItem>
          <PaginationNext asChild>
            <a href="/page/3" />
          </PaginationNext>
        </PaginationItem>
      </PaginationContent>
    </Pagination>;
    ```
  </Tab>
</Tabs>

<Callout title="Framework links">
  Replace `<a href="...">` with your router's `Link` component (Next.js, React
  Router, TanStack Router, etc.) — the composition pattern is router-neutral.
</Callout>

<Callout type="info" title="PaginationPrevious and PaginationNext with asChild">
  You only need to supply the anchor element as the child. The built-in
  ChevronLeft / ChevronRight icon and the visible Previous / Next text are
  rendered automatically alongside your child element.
</Callout>

Use Pagination when users need controlled access to a finite set of pages.

<DocsFeatureGrid
  columns={3}
  tone="platform"
  items={[
  {
    title: "Tables",
    description:
      "Use pagination when dense tables need stable page navigation.",
    icon: Table2,
  },
  {
    title: "Paged data",
    description:
      "Use when the backend or data layer exposes page-based navigation.",
    icon: Database,
  },
  {
    title: "Search results",
    description:
      "Use when results are finite and users need predictable navigation.",
    icon: Rows3,
  },
]}
/>

### Table + Pagination

This example demonstrates a common SaaS pattern: a Table with local Pagination control.

No backend logic is included. Replace the mock slice with your real data layer later.

<Tabs items={["Preview", "Code"]}>
  <Tab value="Preview">
    <Preview>
      <ProjectsTableWithPagination />
    </Preview>
  </Tab>

  <Tab value="Code">
    ```tsx title="projects-table-pagination.tsx"
    type Project = {
      id: string;
      name: string;
      status: "active" | "paused" | "archived";
      updatedAt: string;
    };

    const pageSize = 10;
    const totalPages = Math.ceil(projects.length / pageSize);
    const pageProjects = projects.slice((page - 1) * pageSize, page * pageSize);

    // Pass `page`, `totalPages`, and handlers to Pagination.
    // Keep data slicing, fetching, and URL sync outside the UI primitive.
    ```
  </Tab>
</Tabs>

<Callout type="info" title="Architecture rule">
  Pagination should receive state and callbacks. The feature layer should own
  the data source, filters, sorting, and URL sync.
</Callout>

### buildPaginationRange

Use `buildPaginationRange` to generate compact page tokens with ellipsis.

```tsx title="build-pagination-range.ts"
const tokens = buildPaginationRange({
  page,
  totalPages,
});
```

The returned tokens can represent:

* page numbers
* active page
* ellipsis markers

This keeps rendering logic clean while keeping Pagination controlled.

### Usage patterns

<Steps>
  <Step>
    #### Keep page state outside the component

    Store `page`, `pageSize`, and `totalPages` in the page, feature hook, or data layer.
  </Step>

  <Step>
    #### Disable impossible navigation

    Disable Previous on the first page and Next on the last page.
  </Step>

  <Step>
    #### Use ellipsis for large page counts

    Avoid rendering dozens of page links. Compact large ranges with ellipsis.
  </Step>

  <Step>
    #### Sync URL only at the product layer

    URL syncing belongs to your page or routing layer, not the UI primitive.
  </Step>

  <Step>
    #### Pair with loading and empty states

    Pagination should work with Table, loading states, empty states, and filters as one product pattern.
  </Step>
</Steps>

## Pagination vs infinite scroll

| Situation                            | Use                           |
| ------------------------------------ | ----------------------------- |
| Admin table                          | Pagination                    |
| Search results with known page count | Pagination                    |
| Invoices, users, subscriptions       | Pagination                    |
| Feed-style browsing                  | Infinite scroll               |
| Cursor-only API with no page concept | Product-level cursor controls |
| Small data set                       | No pagination                 |

<Callout title="Decision rule">
  Use Pagination when the user benefits from a stable position in a finite
  result set.
</Callout>

## API

#### Component

| Component            | Description                                     |
| -------------------- | ----------------------------------------------- |
| `Pagination`         | Wrapper `nav` element with pagination semantics |
| `PaginationContent`  | List container                                  |
| `PaginationItem`     | Item wrapper                                    |
| `PaginationLink`     | Page control with active state                  |
| `PaginationPrevious` | Previous button                                 |
| `PaginationNext`     | Next button                                     |
| `PaginationEllipsis` | Visual overflow indicator                       |

#### PaginationLink props

| Prop        | Type      | Default     | Description                                                                   |
| ----------- | --------- | ----------- | ----------------------------------------------------------------------------- |
| `asChild`   | `boolean` | `false`     | Render as a Slot wrapper; supply a real anchor or framework link as the child |
| `isActive`  | `boolean` | `false`     | Marks the current page                                                        |
| `size`      | `string`  | `"icon-sm"` | Maps to Button sizes                                                          |
| `className` | `string`  | —           | Additional Tailwind classes                                                   |

#### PaginationPrevious props

| Prop        | Type      | Default           | Description                                                    |
| ----------- | --------- | ----------------- | -------------------------------------------------------------- |
| `asChild`   | `boolean` | `false`           | Render as a Slot wrapper; built-in icon and text are preserved |
| `label`     | `string`  | `"Previous page"` | Accessible label for screen readers                            |
| `className` | `string`  | —                 | Additional Tailwind classes                                    |

#### PaginationNext props

| Prop        | Type      | Default       | Description                                                    |
| ----------- | --------- | ------------- | -------------------------------------------------------------- |
| `asChild`   | `boolean` | `false`       | Render as a Slot wrapper; built-in icon and text are preserved |
| `label`     | `string`  | `"Next page"` | Accessible label for screen readers                            |
| `className` | `string`  | —             | Additional Tailwind classes                                    |

#### buildPaginationRange options

| Option       | Type     | Description           |
| ------------ | -------- | --------------------- |
| `page`       | `number` | Current page          |
| `totalPages` | `number` | Total number of pages |

### Accessibility

Pagination should be understandable and keyboard accessible.

Guidelines:

* use semantic `nav` with pagination labeling
* mark the active page with `aria-current="page"`
* keep buttons keyboard accessible
* disable Previous and Next when unavailable
* make ellipsis non-interactive
* avoid tiny click targets in dense layouts
* provide URL sync at the page layer when deep linking matters

<Callout title="Accessibility rule">
  Pagination controls should be navigable, understandable, and predictable
  without relying on visual position alone.
</Callout>

## Prefer / avoid

<PreferAvoid
  prefer={[
  "controlled page state",
  "disabled unavailable controls",
  "ellipsis for large page counts",
  "URL sync in the route layer when needed",
  "clear loading and empty states around paged data",
]}
  avoid={[
  "fetching data inside Pagination",
  "rendering every page for large ranges",
  "clickable ellipsis",
  "pagination for tiny data sets",
  "using pagination for feed-style discovery",
]}
/>

### Product copy guidelines

Pagination labels should be short and predictable.

<DocsConceptTabs
  items={[
  {
    value: 'Controls',
    title: 'Previous / Next',
    icon: ChevronRight,
    description: (
      <>
        <p>
          Use familiar labels for core navigation.
          Avoid clever wording or ambiguous actions.
        </p>

        <div className="mt-3 rounded-[5px] border border-border-subtle bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
          Previous · Next
        </div>
      </>
    ),
  },
  {
    value: 'Counts',
    title: 'Showing 1–10 of 48',
    icon: Rows3,
    description: (
      <>
        <p>
          If the table needs stronger context,
          show the current range near pagination controls.
        </p>

        <div className="mt-3 rounded-[5px] border border-border-subtle bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
          Showing 1–10 of 48
        </div>
      </>
    ),
  },
  {
    value: 'Empty',
    title: 'No results found',
    icon: SearchX,
    description: (
      <>
        <p>
          When filters remove all results,
          show a meaningful empty state and a reset action.
        </p>

        <div className="mt-3 rounded-[5px] border border-border-subtle bg-muted/30 px-3 py-2 text-sm text-muted-foreground">
          No results found. Clear filters and try again.
        </div>
      </>
    ),
  },

]}
/>

## Common questions

<Accordions type="single">
  <Accordion title="Should Pagination sync with the URL?">
    Often yes for data-heavy pages, but URL sync belongs in the page or route layer. Pagination should stay UI-only.
  </Accordion>

  <Accordion title="Can Pagination work with cursor-based APIs?">
    Yes, but the cursor logic belongs to the data layer. Use Previous and Next
    controls if numeric pages do not exist.
  </Accordion>

  <Accordion title="When should I hide Pagination?">
    Hide it when there is only one page, when the data set is tiny, or when an
    empty state is shown.
  </Accordion>

  <Accordion title="Should page size be part of Pagination?">
    Usually no. Page size selection is a toolbar or table control. Pagination should focus on page navigation.
  </Accordion>
</Accordions>

## Related

<DocsLinks
  variant="list"
  tone="platform"
  items={[
  {
    title: "Table",
    href: "/docs/ui/table",
    description: "Render structured data that often pairs with Pagination.",
    icon: Table2,
  },
  {
    title: "Data Table Pattern",
    href: "/docs/patterns/data-table",
    description:
      "Combine table, filters, states, actions, and pagination into a full SaaS pattern.",
    icon: Rows3,
  },
  {
    title: "Building a SaaS layout",
    href: "/docs/guides/building-a-saas-layout",
    description: "Place pagination inside real dashboard layouts.",
    icon: LayoutTemplate,
  },
  {
    title: "Empty, loading, and error states",
    href: "/docs/guides/empty-loading-error",
    description: "Handle async states around paged data.",
    icon: LoaderCircle,
  },
]}
/>