# Paging

> The pager, page and page size state, page buttons and sizes, keyboard, localized text, the narrow layout, a custom pager, page methods and events, paging with groups, and cursor paging.

Canonical: https://salmonui.dev/docs/data-grid/paging

`paging` turns paging on: `true` for the defaults, or a `DataGridPaging` object.
Pages are a window over the processed (filtered, sorted, grouped) rows; the
grid never copies rows per page. `paging.pageSize` is the page size, 12 by
default.

```tsx
<DataGrid
  data={orders}
  columns={columns}
  paging={{ pageSize: 20, pageSizeOptions: [10, 20, 50, 'all'] }}
  onPageChange={(event) => console.log(event.page, event.pageSize)}
/>
```

## State and events

`paging.page` is the 1-based page. It is reactive and part of the
server render, so a page can render on the server already on page 3.
`onBeforePageChange` can cancel a change with `preventDefault()`, and
`onPageChange` reports the `page`, `previousPage`, `pageSize` and
`previousPageSize`. Both fire for pager clicks, keys, page size
changes and methods, with `source` telling which.

`api.goToPage(page)` and `api.setPageSize(pageSize)` change the page or the
page size; `api.getPageInfo()` returns the page, page size, page count and total row
count. Going to a page that does not exist is rejected and raises
`onError` with `action: 'page'`. Changing the page size keeps the first row
of the current page in view and clamps to a valid page.

`api.getPageSizeForHeight(height)` returns how many whole rows fit in `height`
px after the toolbar, group drop area, header rows, footer aggregate rows
and pager. Pass the
result to `setPageSize` to fill a container: with `height="auto"` the
grid, its toolbar and its pager then fit the container exactly. Rows count
`rowHeight` (the estimate when rows are measured); before mount only the
header and footer rows are subtracted, and 0 means no row fits.

```tsx
const fit = () => api.current?.setPageSize(Math.max(1, api.current.getPageSizeForHeight(box.clientHeight)));
```

## The pager

The pager shows first, previous, numbered, next and last buttons.
`paging.buttonCount` (default 8) is how many numbered buttons show at once;
the buttons before and after them move to the previous or next set.
`paging.pageSizeOptions` adds a page size dropdown: `true` for
`All, 5, 10, 12, 20`, or your own list where `'all'` shows every row.

The pager is a `role="navigation"` landmark. Its buttons use roving focus:
←/PageUp and →/PageDown move to the previous or next page, Home or
Ctrl+Alt+PageUp to the first and End or Ctrl+Alt+PageDown to the last
page, and Enter or Space activates the focused button; on macOS
the bindings are ←, →, Home and End. Page changes are announced in a live
region ("Page 3 of 12", `localeText.pageOf`).

Every pager string comes from `localeText`: `pagerLabel`, `pagerInfo`
("{page} of {pageCount} pages"), `pagerItems` (with plural forms),
`pageButton`, `pageSize` and the button labels. The pager is a
size container: below 480 px it keeps the current page and the arrows and
hides the other numbered buttons and the item count.

`renderPager(ctx)` replaces the pager. The context has the `page`,
`pageSize`, `pageCount`, `totalRowCount`, the resolved `pageSizeOptions`,
`goToPage`, `setPageSize` and the `defaultPager` element to wrap or
decorate. The prop is reactive: switching between the built-in
and a custom pager on a mounted grid re-renders the pager at once and keeps
the current page, as do changes to the other `paging` options.

### Live demo: Paging

Live demo: https://salmonui.dev/demos/data-grid/paging

The pager with an initial page, page buttons, a page size dropdown, keyboard navigation, localized text, a narrow layout, a custom pager, page methods, the page size that fits a height (getPageSizeForHeight) and cancelable page events.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridLocaleText, type DataGridPagerContext, type DataGridPaging } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(1_000, 3);
const FIT_HEIGHT = 480;

const columns: DataGridColumn<Order>[] = [
  { type: 'rowNumber' },
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

// Starts on page 3 of 100; 5 numeric buttons; a page size dropdown. A constant: the options prop is reactive.
const paging: DataGridPaging = { page: 3, pageSize: 10, buttonCount: 5, pageSizeOptions: [5, 10, 25, 'all'] };

// Pager strings through `localeText` (plural forms for the item count).
const orderText: DataGridLocaleText = { pagerLabel: 'Order pages', pagerInfo: 'Page {page} of {pageCount}', pagerItems: { one: '· 1 order', other: '· {count} orders' }, pageSize: 'Orders per page' };

/** `renderPager`: a compact pager over the pager model. */
function CompactPager(ctx: DataGridPagerContext) {
  return (
    <div className="demo-pager" data-testid="compact-pager" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 12, padding: '8px 12px' }}>
      <Button variant="outline" disabled={ctx.page <= 1} onClick={() => ctx.goToPage(ctx.page - 1)}>
        ‹ Previous
      </Button>
      <span data-testid="compact-pager-info">
        {ctx.page} / {ctx.pageCount} ({ctx.totalRowCount} rows, {ctx.pageSize} per page)
      </span>
      <Button variant="outline" disabled={ctx.page >= ctx.pageCount} onClick={() => ctx.goToPage(ctx.page + 1)}>
        Next ›
      </Button>
    </div>
  );
}

export default function PagingDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [narrow, setNarrow] = useState(false);
  const [custom, setCustom] = useState(false);
  const [orderStrings, setOrderStrings] = useState(false);
  const [lockLast, setLockLast] = useState(false);
  const [fit, setFit] = useState(false);
  const [info, setInfo] = useState('');
  const [log, push] = useEventLog();
  const readInfo = () => {
    const page = api.current?.getPageInfo();
    if (page) setInfo(`page ${page.page} of ${page.pageCount}, ${page.pageSize} per page, ${page.totalRowCount} rows`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={narrow} onCheckedChange={(checked) => setNarrow(checked)}>
          Narrow container (420 px)
        </Checkbox>
        <Checkbox checked={orderStrings} onCheckedChange={(checked) => setOrderStrings(checked)}>
          Custom pager text
        </Checkbox>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Custom pager (renderPager)
        </Checkbox>
        <Checkbox checked={lockLast} onCheckedChange={(checked) => setLockLast(checked)}>
          Cancel moves to the last page
        </Checkbox>
        <Checkbox checked={fit} onCheckedChange={(checked) => setFit(checked)}>
          Fit pages to a {FIT_HEIGHT} px box
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.goToPage(1)}>
          Go to page 1
        </Button>
        <Button variant="outline" onClick={() => api.current?.goToPage(50)}>
          Go to page 50
        </Button>
        <Button variant="outline" onClick={() => api.current?.setPageSize(25)}>
          25 per page
        </Button>
        <Button variant="outline" onClick={readInfo}>
          Read page info
        </Button>
      </div>
      <div style={{ ...(narrow ? { maxInlineSize: 420 } : {}), ...(fit ? { blockSize: FIT_HEIGHT, outline: '1px dashed currentColor' } : {}) }} data-testid="paging-box">
        {/* `renderPager` is reactive: switching it keeps the grid and its current page. */}
        <DataGrid<Order>
          aria-label="Paged orders"
          data={orders}
          columns={columns}
          paging={paging}
          {...(custom ? { renderPager: CompactPager } : {})}
          {...(orderStrings ? { localeText: orderText } : {})}
          // Fit mode: a new grid with auto height whose page size fills the box (getPageSizeForHeight).
          key={fit ? 'fit' : 'fixed'}
          height={fit ? 'auto' : 360}
          onReady={(grid) => {
            if (!fit) return;
            const size = grid.getPageSizeForHeight(FIT_HEIGHT);
            push(`getPageSizeForHeight(${FIT_HEIGHT}): ${size} rows`);
            if (size > 0) grid.setPageSize(size);
          }}
          locale="en-US"
          currency="USD"
          timeZone="UTC"
          ref={api}
          onBeforePageChange={(event) => {
            if (lockLast && event.page === api.current?.getPageInfo()?.pageCount) {
              event.preventDefault();
              push(`beforePageChange to ${event.page}: canceled`);
            }
          }}
          onPageChange={(event) => push(`pageChange (${event.source}): page ${event.previousPage} → ${event.page}, size ${event.previousPageSize} → ${event.pageSize}`)}
          onError={(event) => push(`error (${event.action}): ${event.error.message}`)}
        />
      </div>
      <p className="demo-status" role="status" data-testid="page-info">
        {info || 'Use the pager buttons, or focus one and press ←, →, Home or End.'}
      </p>
      <EventLog entries={log} label="Page events" />
    </>
  );
}
```

## Paging with groups

With grouping, pages count data rows. A page shows the captions and
footers of the groups it intersects, so a group that spans two pages has
its caption on both, and a collapsed group still occupies its rows of the
page. `aggregateScope` decides whether aggregates cover the
current page (the default) or every row; see [Aggregates](https://salmonui.dev/docs/data-grid/aggregates).

### Live demo: Paged groups and aggregate scope

Live demo: https://salmonui.dev/demos/data-grid/paged-groups

400 orders grouped by country and paged 25 data rows at a time; `aggregateScope` switches the footer and group footers between the current page and every row.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridAggregateContext, type DataGridAggregateRow, type DataGridColumn } from '@salmonui/data-grid';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(400, 17);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 230 },
];

// Module-level templates and definitions: stable across renders.
const amountFooter = ({ formatted, values }: DataGridAggregateContext<Order>) => (
  <span data-testid="amount-footer">
    {String(values['count'])} orders · Σ {formatted['sum']}
  </span>
);
const amountGroupFooter = ({ formatted, values }: DataGridAggregateContext<Order>) => (
  <span>
    {String(values['count'])} orders · Σ {formatted['sum']}
  </span>
);
const amountTypes = ['sum', 'count'] as const;
const aggregates: DataGridAggregateRow<Order>[] = [{ columns: [{ field: 'amount', type: amountTypes, format: 'C2', renderFooter: amountFooter, renderGroupFooter: amountGroupFooter }] }];
const grouping = { groupBy: ['country'], showGroupedColumns: true };
const paging = { pageSize: 25 };

export default function PagedGroupsDemo() {
  const [scope, setScope] = useState<'page' | 'all'>('page');
  return (
    <>
      <div className="demo-toolbar">
        <RadioGroup label="Aggregate scope" name="aggregate-scope" orientation="horizontal" value={scope} onValueChange={(value) => setScope(value as 'page' | 'all')}>
          <Radio value="page">Aggregate the current page</Radio>
          <Radio value="all">Aggregate every row</Radio>
        </RadioGroup>
      </div>
      <DataGrid<Order>
        aria-label="Grouped orders, 25 per page, with page-wise or whole aggregates"
        data={orders}
        columns={columns}
        grouping={grouping}
        paging={paging}
        aggregates={aggregates}
        aggregateScope={scope}
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">Pages count data rows; captions and footers of the groups on a page come along. Change the page and watch the footer.</p>
    </>
  );
}
```

## Remote and cursor paging

With a remote data source the page is part of every read request; see
[Server paging and the URL](https://salmonui.dev/docs/data-grid/url-paging). A JSON data source created
with `paging: { kind: 'cursor' }` pages with cursors instead of offsets:
the server answers each page with the cursor of the next one,
and the next request carries it. The source knows a page's cursor only
after reading the page before it, so a jump to a page that was not reached
yet is rejected with `CursorUnknownError`; walk the pages in order.

### Live demo: Cursor paging

Live demo: https://salmonui.dev/demos/data-grid/cursor-paging

Remote paging with cursors instead of offsets; each page request carries the cursor the server returned with the previous page.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createJsonDataSource } from '@salmonui/data';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

const columns: DataGridColumn<RemoteOrder>[] = [
  { type: 'rowNumber' },
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

const paging = { pageSize: 25 };

export default function CursorPagingDemo() {
  const [log, push] = useEventLog();
  // Cursor paging: page n + 1 is requested with the cursor the server returned for page n.
  const [source] = useState(() =>
    createJsonDataSource<RemoteOrder>({
      url: '/api/orders?delay=120',
      fetch: demoFetch,
      key: 'id',
      paging: { kind: 'cursor' },
      onResponse: (event) => {
        if (!('query' in event.request) || !('rows' in event.response)) return;
        push(`page ${JSON.stringify(event.request.query.page)} → next ${JSON.stringify(event.response.next ?? null)}`);
      },
    }),
  );
  return (
    <>
      <DataGrid<RemoteOrder>
        aria-label="Remote orders paged with cursors"
        data={source}
        columns={columns}
        paging={paging}
        onError={(event) => push(`error (${event.action}): ${event.error.message}`)}
        height={360}
        locale="en-US"
        currency="USD"
      />
      <p className="demo-status">Use Next page: each request carries the cursor of the previous response.</p>
      <EventLog entries={log} label="Cursor requests" />
    </>
  );
}
```

## API reference

See [`DataGridPaging`](https://salmonui.dev/docs/reference/data-grid/DataGridPaging),
[`DataGridPagerContext`](https://salmonui.dev/docs/reference/data-grid/DataGridPagerContext)
and [`DataGridPageChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridPageChangeEvent)
in the API reference.
