# Pinned rows

> Pin records to the top of the grid by data or at runtime; pinned rows follow sorting, filtering and edits and stay outside the page size.

Canonical: https://salmonui.dev/docs/data-grid/pinned-rows

Pinned rows are records shown in a fixed zone
above the scrolling rows. Unlike `stickyRows`, which keeps the first N
positions of the view in place, pinning follows the record: a pinned order
stays on top whatever the sort, page or scroll position.

## Pinning rows

`isRowPinned(row)` pins rows by data. It must be
pure; the grid reads it when it is created and calls it once per row of a
data array, again only for rows that are added or changed, so edits that
make a row match pin it.

`defaultPinnedRows` pins rows by id when the grid is created. Either prop
turns pinning on; pass `defaultPinnedRows={[]}` to pin only from code.

```tsx
<DataGrid
  data={orders}
  columns={columns}
  isRowPinned={(order) => order.priority === 'High'}
  ref={api}
/>

api.current?.pinRows(['ORD-1042']);
api.current?.unpinRows('ORD-1042');
api.current?.isRowPinned('ORD-1042'); // false
api.current?.getPinnedRowIds();      // pinned rows shown, in display order
```

`unpinRows` also unpins rows that `isRowPinned` matches, and `pinRows`
undoes that. Rows are identified by their row id, so the grid needs a
`primaryKey` column or `getRowId`.

## Sorting, filtering, paging and editing

- A pinned row is shown once: it leaves its place among the scrolling rows.
- Pinned rows are sorted among themselves by the current sort.
- A pinned row that the filter or search excludes is hidden, and comes back
  pinned when the filter changes.
- Pinned rows are not counted in `pageSize` or the page count: every page
  shows the pinned rows above its own rows.
- Edits, adds and deletes update pinned rows like any other row.
- Footer aggregates include the pinned rows (the page-wise footer counts the
  pinned rows and the page). Select all selects them too.
- While grouping, pinned rows stay above the groups and belong to none;
  pinned rows show no detail toggle or detail row (see
  [Detail rows](https://salmonui.dev/docs/data-grid/detail-rows)).
- Pinned rows are neither drag sources nor drop targets for row drag
  (see [Row drag](https://salmonui.dev/docs/data-grid/row-drag)).

## Layout, keyboard and accessibility

Pinned rows render first in the sticky top rowgroup, followed by the
`stickyRows` rows, and carry `data-pinned`. The virtual row window never
contains them, and pinned columns intersect them like any row. Their
`aria-rowindex` follows the visible order, so arrow keys move from the last
pinned row to the first scrolling row and back.

## State and export

`getState()` stores the pins and unpins made by id under `pinnedRows`
(rows pinned by `isRowPinned` need no state), and `restoreState()` applies
them; exclude the part with `exclude: ['pinnedRows']`. Ungrouped exports
list the pinned rows first, as the grid shows them.

With a remote data source the grid can only pin rows the server returned
for the current page.

### Live demo: Pinned rows

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

Rows pinned by `isRowPinned` and at runtime with `api.pinRows` / `api.unpinRows` stay in the sticky top zone of 2,000 virtualized orders, follow sorting, filtering and search, and stay outside `pageSize`.

`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 DataGridFiltering, type DataGridPaging } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { useDemoStore } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(2_000, 23);

const columns: DataGridColumn<Order>[] = [
  { type: 'selection', width: 44 },
  { field: 'id', header: 'Order', primaryKey: true, width: 110, pinned: 'start' },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'priority', header: 'Priority', width: 100 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120, pinned: 'end' },
];

// Pinned by data: the first three High-priority orders of the fixture (pure, read once).
const highlighted = new Set(orders.filter((o) => o.priority === 'High').slice(0, 3).map((o) => o.id));
const isRowPinned = (order: Order) => highlighted.has(order.id);

const filtering: DataGridFiltering = { ui: 'row' };
const paged: DataGridPaging = { pageSize: 10 };
const toolbar = ['search'] as const;
const STICKY_ROWS = [0, 1, 2].map((n) => ({ value: String(n), label: String(n) }));

export default function PinnedRowsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [paging, setPaging] = useState(false);
  const [stickyRows, setStickyRows] = useState(0);
  const [pinned, pinnedStore] = useDemoStore<readonly string[]>([]);
  const refresh = () => pinnedStore.set(api.current?.getPinnedRowIds() ?? []);
  const selected = () => api.current?.getSelectedRowIds() ?? [];
  return (
    <>
      <div className="demo-toolbar">
        <Button
          variant="outline"
          onClick={() => {
            api.current?.pinRows(selected());
            refresh();
          }}
        >
          Pin selected rows
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.unpinRows(selected());
            refresh();
          }}
        >
          Unpin selected rows
        </Button>
        <Checkbox checked={paging} onCheckedChange={(checked) => setPaging(checked)}>
          Paging (10 per page)
        </Checkbox>
        <label>
          Sticky rows below the pinned rows
          <Select aria-label="Sticky rows below the pinned rows" data={STICKY_ROWS} value={String(stickyRows)} onValueChange={(value) => value != null && setStickyRows(Number(value))} />
        </label>
      </div>
      <DataGrid<Order>
        aria-label="Orders with pinned rows"
        data={orders}
        columns={columns}
        isRowPinned={isRowPinned}
        stickyRows={stickyRows}
        selection={{ multiple: true }}
        sorting
        filtering={filtering}
        search
        toolbar={toolbar}
        paging={paging ? paged : false}
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onReady={(grid) => pinnedStore.set(grid.getPinnedRowIds())}
        onViewChange={refresh}
      />
      <p className="demo-status" aria-live="polite">
        Pinned rows shown: {pinned.length ? pinned.join(', ') : 'none'}
      </p>
    </>
  );
}
```

## API reference

[`DataGridProps`](https://salmonui.dev/docs/reference/data-grid/DataGridProps) lists
`isRowPinned` and `defaultPinnedRows`, and
[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi) `pinRows`,
`unpinRows`, `isRowPinned` and `getPinnedRowIds`.
