# Pagination

> Split rows into client-side pages, choose a page size and control the current page from code.

Birch UI Grid virtualizes rows, so it does not need pagination for performance: a hundred thousand rows scroll smoothly. Use pagination when the interface calls for pages, for example in an admin table where users refer to "page 3", or when a design puts the grid inside a fixed-height card.

## Turning pagination on

```ts title="paged-invoices.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

const columns: ColumnDef<Invoice>[] = [
  { field: 'number', header: 'Invoice', width: 130 },
  { field: 'customer', flex: 1 },
  { field: 'issued', type: 'date' },
  { field: 'amount', type: 'number' },
  { field: 'paid', type: 'boolean' },
];

const grid = createGrid<Invoice>(document.querySelector('#invoices')!, {
  columns,
  rows: invoices,
  getRowId: (i) => i.number,
  pagination: { pageSize: 25 },
});
```

`pagination` accepts:

| Value | Meaning |
| --- | --- |
| `false` or omitted | No pagination. All display rows are scrollable. |
| `true` | Pagination with 100 rows per page. |
| `{ pageSize, page? }` | Pagination with your page size, optionally starting on a page other than the first. |

**`PaginationOptions`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface PaginationOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `pageSize` | `number` |  |
| `page?` | `number` |  |

Pages are zero-based: `page: 0` is the first page. Pagination runs after every stage of the row pipeline, including filtering, sorting and module stages such as grouping, so each page holds a slice of the final display rows.

## Navigating pages

The grid renders a pager in its bottom slot, with first, previous, next and last buttons, the range shown ("101–200 of 1,250") and "Page 2 of 13". The page label is a polite live region, so screen readers announce page changes. From code:

```ts
grid.setPage(0);
grid.setPage(grid.getPage() + 1);
grid.setPage(grid.getPageCount() - 1);
```

`setPage()` clamps to the valid range, so you do not need to check bounds before calling it. It scrolls the grid back to the top and fires `pageChanged`.

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `setPage` | `(page: number) => void` |  |
| `getPage` | `() => number` |  |
| `getPageCount` | `() => number` |  |

## Building your own pager

Listen to `pageChanged` to keep custom controls in sync. It fires whenever the current page changes: through the pager, `setPage()` or `update({ pagination })`, when a filter change returns the grid to the first page, and when new data leaves fewer pages than the current one. A change in the page count alone, such as rows added to the last page, does not fire it, so also refresh your controls on `modelUpdated`.

```ts
const label = document.querySelector('#page-label')!;
const prev = document.querySelector<HTMLButtonElement>('#prev-page')!;
const next = document.querySelector<HTMLButtonElement>('#next-page')!;

function render(page: number, pageCount: number) {
  label.textContent = pageCount === 0 ? 'No invoices' : `Page ${page + 1} of ${pageCount}`;
  prev.disabled = page <= 0;
  next.disabled = page >= pageCount - 1;
}

grid.on('pageChanged', ({ page, pageCount }) => render(page, pageCount));
grid.on('modelUpdated', () => render(grid.getPage(), grid.getPageCount()));
prev.addEventListener('click', () => grid.setPage(grid.getPage() - 1));
next.addEventListener('click', () => grid.setPage(grid.getPage() + 1));
render(grid.getPage(), grid.getPageCount());
```

## Changing the page size

```ts
const sizeSelect = document.querySelector<HTMLSelectElement>('#page-size')!;
sizeSelect.addEventListener('change', () => {
  grid.update({ pagination: { pageSize: Number(sizeSelect.value), page: 0 } });
});
```

Changing `pagination` through `update()` moves to the `page` given in the new value, or to the first page when it is omitted.

## Pagination and other features

- **Display rows are the current page.** Pagination is applied after the row pipeline, so `getDisplayRows()` returns the rows of the current page, and row indexes in events and in calls such as `focusCell()` and `scrollToRow()` refer to positions within that page. `getAllDisplayRows()` returns the display rows of every page, which is what CSV export and the select-all checkbox work on.
- **Filters reset the page.** Any filter or quick filter change, from the UI, the API or `update()`, returns to the first page and fires `pageChanged` when the page actually changes.
- **Sorting and filtering** apply to all rows, then the result is paged. `modelUpdated` reports the total number of source rows in `rowCount`.
- **Selection** is stored by row ID, so selected rows stay selected when the user changes pages. `selectAll()` and the select-all checkbox select matching rows on every page.
- **Accessibility**: `aria-rowcount` reports all rows across pages and each row's `aria-rowindex` is its position in the full result, so screen readers announce "row 230 of 1,250" on page 3.
- **CSV export** includes the matching rows of every page, not only the current one.

## Server-side paging

For datasets that live on a server, keep pagination off in the grid and load one page at a time with `setRows()`:

```ts
let page = 0;
const pageSize = 100;

async function loadPage(nextPage: number) {
  const response = await fetch(`/api/invoices?offset=${nextPage * pageSize}&limit=${pageSize}`);
  const { items, total } = await response.json();
  page = nextPage;
  grid.setRows(items);
  label.textContent = `Page ${page + 1} of ${Math.ceil(total / pageSize)}`;
}

grid.on('sortChanged', () => loadPage(0));
grid.on('filterChanged', () => loadPage(0));
await loadPage(0);
```
