
# Pagination

**Page links or buttons for a list that is split into pages.**

**Reference:** [View Source](https://github.com/jramke/fluid-primitives/tree/main/Resources/Private/Primitives/Pagination) · [Zag.js Docs](https://zagjs.com/components/react/pagination)

**PaginationExamples.html**

```html
<ui:pagination.root count="120">
    <ui:context name="ui:pagination" as="paginationContext" />
    <ui:pagination.prevTrigger />
    <f:for each="{paginationContext.pages}" as="page">
        <f:if condition="{page.type} == 'page'">
            <f:then><ui:pagination.item value="{page.value}" /></f:then>
            <f:else><ui:pagination.ellipsis index="{page.index}" /></f:else>
        </f:if>
    </f:for>
    <primitives:pagination.itemTemplate>
        <ui:pagination.item />
    </primitives:pagination.itemTemplate>
    <primitives:pagination.ellipsisTemplate>
        <ui:pagination.ellipsis />
    </primitives:pagination.ellipsisTemplate>
    <ui:pagination.nextTrigger />
</ui:pagination.root>

```

**Pagination.entry.ts**

```ts
import { mountAll } from 'fluid-primitives';
import { Pagination } from 'fluid-primitives/pagination';

mountAll('ui:pagination', ({ props }) => new Pagination(props).init());

```

## Features

- Takes the paginator of TYPO3's pagination API
- Renders links that reload the page, or buttons that change the page on the client
- Shows the first and last pages and an ellipsis for the pages in between
- Labels every page and trigger for screen readers

## Anatomy

```html
<primitives:pagination.root>
    <primitives:pagination.firstTrigger />
    <primitives:pagination.prevTrigger />
    <primitives:pagination.item />
    <primitives:pagination.ellipsis />
    <primitives:pagination.itemTemplate />
    <primitives:pagination.ellipsisTemplate />
    <primitives:pagination.nextTrigger />
    <primitives:pagination.lastTrigger />
</primitives:pagination.root>
```

The context of the root holds the `pages` to show, each with a `type` (`page` or `ellipsis`), a `value` and an `index`. Loop over them with `ui:context`:

```html
<ui:pagination.root count="120">
    <ui:context name="ui:pagination" as="paginationContext" />
    <ui:pagination.prevTrigger />
    <f:for each="{paginationContext.pages}" as="page">
        <f:if condition="{page.type} == 'page'">
            <f:then><ui:pagination.item value="{page.value}" /></f:then>
            <f:else><ui:pagination.ellipsis index="{page.index}" /></f:else>
        </f:if>
    </f:for>
    <primitives:pagination.itemTemplate>
        <ui:pagination.item />
    </primitives:pagination.itemTemplate>
    <primitives:pagination.ellipsisTemplate>
        <ui:pagination.ellipsis />
    </primitives:pagination.ellipsisTemplate>
    <ui:pagination.nextTrigger />
</ui:pagination.root>
```

An item without content shows its page number, an ellipsis shows `…`. With `itemTemplate` and `ellipsisTemplate`, the client renders the pages when the page changes without a reload.

## Installation

```bash
typo3 ui:add pagination
```

Or copy the files manually from GitHub into your project: https://github.com/jramke/fluid-primitives/tree/main/Resources/Private/Registry/Pagination

Read more about installing [Components and Primitives](/docs/core-concepts/primitives.md).

## Examples

### Paginate a TYPO3 list

Pass the paginator of your list action to `paginator`, not a TYPO3 pagination: the root works out which pages to show. For links, wrap it in a `UrlAwarePaginator` with a function that builds the URL of a page, for example with the `UriBuilder`, which adds the cHash. The root builds the URLs of the pages it shows.

```php
public function listAction(int $currentPage = 1): ResponseInterface
{
    $paginator = new UrlAwarePaginator(
        new QueryResultPaginator($this->eventRepository->findAll(), $currentPage, 4),
        fn(int $page): string => $this->uriBuilder->reset()
            ->setSection('event-list')
            ->uriFor(null, ['currentPage' => $page]),
    );
    $this->view->assign('paginator', $paginator);

    return $this->htmlResponse();
}
```

**PaginationExamples.html**

```html
<div class="flex w-full max-w-md flex-col gap-4">
    <ul class="divide-y rounded-md border text-sm">
        <f:for each="{paginator.paginatedItems}" as="event">
            <li class="flex justify-between gap-4 px-4 py-2">
                <span>{event.title}</span>
                <span class="text-muted-foreground">{event.city}</span>
            </li>
        </f:for>
    </ul>
    <ui:pagination.root paginator="{paginator}" defaultPageSize="4">
        <ui:context name="ui:pagination" as="paginationContext" />
        <ui:pagination.prevTrigger />
        <f:for each="{paginationContext.pages}" as="page">
            <f:if condition="{page.type} == 'page'">
                <f:then><ui:pagination.item value="{page.value}" /></f:then>
                <f:else><ui:pagination.ellipsis index="{page.index}" /></f:else>
            </f:if>
        </f:for>
        <ui:pagination.nextTrigger />
    </ui:pagination.root>
</div>

```

### Load pages without a reload

Pass your endpoint to `fetchUrl`, here the same list action with `format` `json`, render the root with `autoMount="{false}"` and mount it yourself with a `loadPage` function. It loads and shows a page after every page change: pass its `signal` to the request, so a response of a page that is no longer current is dropped. A click on a link no longer loads its URL: the address bar follows the page, and back and forward change it. For that, the server sends the URL of every page to the client.

```php
public function listAction(int $currentPage = 1): ResponseInterface
{
    $paginator = new UrlAwarePaginator(/* as above */);

    if ($this->request->getFormat() === 'json') {
        $events = array_map(
            static fn(Event $event): array => ['title' => $event->getTitle(), 'city' => $event->getCity()],
            [...$paginator->getPaginatedItems()],
        );
        return $this->jsonResponse(json_encode(['events' => $events]));
    }

    $this->view->assign('paginator', $paginator);

    return $this->htmlResponse();
}
```

**PaginationExamples.html**

```html
<ui:pagination.root
    rootId="event-archive"
    autoMount="{false}"
    paginator="{paginator}"
    defaultPageSize="4"
    fetchUrl="{f:uri.action(action: 'list', controller: 'EventArchive', format: 'json')}"
    class="w-full max-w-md flex-col items-stretch gap-4">
    <ui:context name="ui:pagination" as="paginationContext" />
    <ul
        {ui:ref(name: 'events', context: 'pagination')}
        class="divide-y rounded-md border text-sm">
        <f:for each="{paginator.paginatedItems}" as="event">
            <li class="flex justify-between gap-4 px-4 py-2">
                <span>{event.title}</span>
                <span class="text-muted-foreground">{event.city}</span>
            </li>
        </f:for>
    </ul>
    <ui:template name="eventTemplate" context="pagination">
        <li class="flex justify-between gap-4 px-4 py-2">
            <span {ui:ref(name: 'title')}></span>
            <span class="text-muted-foreground" {ui:ref(name: 'city')}></span>
        </li>
    </ui:template>
    <div class="flex items-center gap-1">
        <ui:pagination.prevTrigger />
        <f:for each="{paginationContext.pages}" as="page">
            <f:if condition="{page.type} == 'page'">
                <f:then><ui:pagination.item value="{page.value}" /></f:then>
                <f:else><ui:pagination.ellipsis index="{page.index}" /></f:else>
            </f:if>
        </f:for>
        <primitives:pagination.itemTemplate>
            <ui:pagination.item />
        </primitives:pagination.itemTemplate>
        <primitives:pagination.ellipsisTemplate>
            <ui:pagination.ellipsis />
        </primitives:pagination.ellipsisTemplate>
        <ui:pagination.nextTrigger />
    </div>
</ui:pagination.root>

<vite:asset entry="EXT:docs/Resources/Private/Components/ui/PaginationExamples/FetchWithUrl.entry.ts" />

```

**FetchWithUrl.entry.ts**

```ts
import { extbase, mount, Template } from 'fluid-primitives';
import { Pagination } from 'fluid-primitives/pagination';

interface ArchiveEvent {
    title: string;
    city: string;
}

mount('ui:pagination', 'event-archive', ({ props }) => {
    const pagination: Pagination = new Pagination({
        ...props,
        loadPage: async ({ page, fetchUrl, signal }) => {
            const response = await extbase.post(fetchUrl, { currentPage: page }, { signal });
            const { events } = (await response.json()) as { events: ArchiveEvent[] };

            pagination.hydrator.query('events')!.replaceChildren(
                ...events.map(({ title, city }) => {
                    const row = new Template(pagination.hydrator, 'eventTemplate');
                    row.query('title')!.textContent = title;
                    row.query('city')!.textContent = city;
                    return row;
                })
            );
        },
    });
    return pagination.init();
});

```

### Show a window of pages

With `boundaryCount="0"` and no ellipsis in the loop, the pagination shows a window of pages around the current one. `siblingCount` sets its width.

**PaginationExamples.html**

```html
<ui:pagination.root count="1000" defaultPageSize="20" defaultPage="22" siblingCount="2" boundaryCount="0">
    <ui:context name="ui:pagination" as="paginationContext" />
    <ui:pagination.prevTrigger />
    <f:for each="{paginationContext.pages}" as="page">
        <f:if condition="{page.type} == 'page'">
            <ui:pagination.item value="{page.value}" />
        </f:if>
    </f:for>
    <primitives:pagination.itemTemplate>
        <ui:pagination.item />
    </primitives:pagination.itemTemplate>
    <ui:pagination.nextTrigger />
</ui:pagination.root>

```

### Jump to the first and last page

Add `firstTrigger` and `lastTrigger`.

**PaginationExamples.html**

```html
<ui:pagination.root count="500" defaultPage="12" siblingCount="2">
    <ui:context name="ui:pagination" as="paginationContext" />
    <ui:pagination.firstTrigger />
    <ui:pagination.prevTrigger />
    <f:for each="{paginationContext.pages}" as="page">
        <f:if condition="{page.type} == 'page'">
            <f:then><ui:pagination.item value="{page.value}" /></f:then>
            <f:else><ui:pagination.ellipsis index="{page.index}" /></f:else>
        </f:if>
    </f:for>
    <primitives:pagination.itemTemplate>
        <ui:pagination.item />
    </primitives:pagination.itemTemplate>
    <primitives:pagination.ellipsisTemplate>
        <ui:pagination.ellipsis />
    </primitives:pagination.ellipsisTemplate>
    <ui:pagination.nextTrigger />
    <ui:pagination.lastTrigger />
</ui:pagination.root>

```

## API Reference

### pagination.root

Provides the pages and labels the navigation. Renders a `<nav>` element.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `paginator` | `TYPO3\CMS\Core\Pagination\PaginatorInterface` | No | `-` | The TYPO3 paginator of the list, e.g. an `ArrayPaginator` or a `QueryResultPaginator`. Wrap it in a `UrlAwarePaginator` for links. It sets the current page and the number of pages. |
| `count` | `integer` | No | `-` | The total number of items, which sets the number of pages together with `defaultPageSize`. Leave it out with a `paginator`. |
| `defaultPage` | `integer` | No | `-` | The page that is current when rendered, 1 by default. Leave it out with a `paginator`, which sets it. |
| `defaultPageSize` | `integer` | No | `10` | The number of items per page. With a `paginator`, set it to the items per page of the paginator, so the page size in `onPageChange` matches. |
| `siblingCount` | `integer` | No | `1` | The number of pages shown on each side of the current page. |
| `boundaryCount` | `integer` | No | `1` | The number of pages always shown at the start and at the end. |
| `pageUrls` | `array` | No | `-` | The URL of every page, keyed by the page number starting at 1, for links without a `UrlAwarePaginator`. Leave it out with one. With it, the items and triggers are links to their page. |
| `fetchUrl` | `string` | No | `-` | The endpoint your client script loads the content of a page from: the library passes it to your `loadPage` and sends no request itself. With links, a click on a page no longer loads it: the URL in the address bar follows the page, and back and forward change it. Buttons have no URL, so the history stays as it is. |
| `translations` | `array` | No | `-` | Localized labels: `rootLabel`, `firstTriggerLabel`, `prevTriggerLabel`, `nextTriggerLabel`, `lastTriggerLabel` and `itemLabel`, which takes a `%page%` and a `%totalPages%` placeholder. A client script can pass Zag's `itemLabel` function instead. |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `rootId` | `string` | No | `-` | The root ID of the component, used for hydration and identification. |
| `ids` | `array` | No | `[]` | The IDs of of the component parts for composition. |
| `autoMount` | `boolean` | No | `true` | Whether the client initializes the component on its own. Set it to false to mount it yourself with `mount()` |
| `provider` | `string` | No | `-` | The `id` of the `.provider` this root takes its `rootId` and props from. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

### pagination.item

Goes to one page. Renders an `<a>` element with a `UrlAwarePaginator` or `pageUrls`, a `<button>` element otherwise.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `value` | `integer` | No | `-` | The page number of the item. Without content, the item shows it. Left out in the `itemTemplate`, where the client sets it. |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-item` | <uid> |
| `data-index` | The index of the item |
| `data-selected` | Present when selected |

### pagination.ellipsis

Stands for the pages that are left out. Renders a `<span>` element.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `index` | `integer` | No | `-` | The position of the ellipsis among the pages, the `index` of its entry in `pages`. |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-ellipsis` | <uid> |
| `data-index` | The index of the item |

### pagination.itemTemplate

Holds the item the client clones for a page it renders. Renders a `<template>` element.

### pagination.ellipsisTemplate

Holds the ellipsis the client clones. Renders a `<template>` element.

### pagination.firstTrigger

Goes to the first page. Renders an `<a>` or a `<button>` element, as the item.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-first-trigger` | <uid> |
| `data-disabled` | Present when disabled |

### pagination.prevTrigger

Goes to the previous page. Renders an `<a>` or a `<button>` element, as the item.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-prev-trigger` | <uid> |
| `data-disabled` | Present when disabled |

### pagination.nextTrigger

Goes to the next page. Renders an `<a>` or a `<button>` element, as the item.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-next-trigger` | <uid> |
| `data-disabled` | Present when disabled |

### pagination.lastTrigger

Goes to the last page. Renders an `<a>` or a `<button>` element, as the item.

| Name | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `attributes` | `array` | No | `[]` | Additional attributes that should be rendered on the component where ui:attributes is used. |
| `asChild` | `boolean` | No | `-` | If true the component uses its child only without the component template. Like Radix UI asChild or Base UI render props. |
| `class` | `string` | No | `-` | The CSS class(es) to be applied to the component. |

#### Rendered data attributes

| Attribute | Description |
| --- | --- |
| `data-pagination-last-trigger` | <uid> |
| `data-disabled` | Present when disabled |

### Machine JavaScript API

| Name | Type | Description |
| --- | --- | --- |
| `page` | `number` | The current page. |
| `count` | `number` | The total number of data items. |
| `pageSize` | `number` | The number of data items per page. |
| `totalPages` | `number` | The total number of pages. |
| `pages` | `Pages` | The page range. Represented as an array of page numbers (including ellipsis) |
| `previousPage` | `number \| null` | The previous page. |
| `nextPage` | `number \| null` | The next page. |
| `pageRange` | `PageRange` | The page range. Represented as an object with `start` and `end` properties. |
| `slice` | `<V>(data: V[]) => V[]` | Function to slice an array of data based on the current page. |
| `setPageSize` | `(size: number) => void` | Function to set the page size. |
| `setPage` | `(page: number) => void` | Function to set the current page. |
| `goToNextPage` | `VoidFunction` | Function to go to the next page. |
| `goToPrevPage` | `VoidFunction` | Function to go to the previous page. |
| `goToFirstPage` | `VoidFunction` | Function to go to the first page. |
| `goToLastPage` | `VoidFunction` | Function to go to the last page. |
| `getItemState` | `(props: ItemProps) => ItemState` | Returns the state of a pagination item |
