# Toolbar

> Built-in and custom toolbar items, alignment, search, overflow, keyboard navigation and a replaceable toolbar.

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

The `toolbar` prop lists the items in order. The toolbar renders as a
`role="toolbar"` element just before the `role="grid"` element, not inside
it: a grid may only own rows, so a toolbar inside it would break the grid
semantics. In DOM order the toolbar comes first, so Tab reaches the toolbar
and then the grid's single tab stop.

## Built-in items

Built-in items are plain ids: `'add'`, `'edit'`, `'delete'`,
`'save'`, `'cancel'`, `'search'`, `'print'`, `'columnChooser'`,
`'exportExcel'`, `'exportPdf'` and `'exportCsv'`, plus the Salmon UI
additions `'expandAll'` and `'collapseAll'` for groups, `'copy'` (copies the
selection), `'filterBuilder'` (opens the filter builder; needs
`filtering.builder`, see [Filtering](https://salmonui.dev/docs/data-grid/filtering)), and
`'indent'` and `'outdent'` for tree rows (see [Tree Grid](https://salmonui.dev/docs/data-grid/tree)).
`'search'` renders a search box bound to the grid search (it needs the
`search` prop), and `'columnChooser'` opens the column chooser below the
button.

Edit, copy, export, print and tree items run named UI commands
(`edit.add`, `clipboard.copy`, `export.csv`, `grid.print`, `tree.indent`,
...). An item is enabled when something serves
its command: a handler registered with `api.registerCommandHandler`, or a
registered module that declares it. Otherwise the item is disabled with the
reason as its tooltip.

With editing on, the edit items also follow the edit state. `'add'`, `'edit'` and `'delete'` need `editing.add`, `editing.edit`
and `editing.delete`; `'edit'` and `'delete'` also need a target row: a
selected row or cell range, or with selection off the focused body cell.
In row, dialog and cell mode an open edit disables `'add'`, `'edit'` and
`'delete'`, and only then are `'save'` (Update) and `'cancel'` enabled. In
batch mode `'save'` and `'cancel'` are enabled while there are pending
changes (edited, added or deleted rows) or a cell editor is open. These
items are `aria-disabled` and do nothing until the state changes; the
toolbar re-renders only when an item's enablement can change, never per
cell or keystroke.

```tsx
<DataGrid
  aria-label="Orders"
  data={orders}
  columns={columns}
  grouping
  toolbar={['expandAll', 'collapseAll', { id: 'columnChooser', label: 'Columns' }, 'exportCsv', 'search']}
  search
  onReady={(api) => api.registerCommandHandler('export.csv', () => { /* export */ return true; })}
/>
```

## Custom items

An item object is a `DataGridToolbarItem`: `id`, `label`, `icon`,
`title` (tooltip), `align`, `disabled` and `render` for custom content. An
object whose `id` is a built-in id keeps the built-in behavior and takes the
new label, icon, title, alignment or `disabled`. `disabled` is reactive:
pass a new value and the item updates.

Give a `render` item a `label`: it names the button (`aria-label`, so an
icon-only render stays accessible) and is the item's text in the overflow
menu. Without one the menu falls back to `title`, then the rendered text
or `aria-label`, then the id, and development builds warn once.

Items align to the `start` (default), `center` or `end` of the toolbar;
the search box defaults to `end`.

`onToolbarItemClick` reports every click with the item; calling
`event.preventDefault()` skips the built-in action. `renderToolbar` replaces
the toolbar and receives the resolved `items`, the `defaultToolbar` element
to wrap and the grid `api`.

## Overflow and keyboard

When the items do not fit, the trailing items move into a "more" menu at
the end of the toolbar; the search box always stays visible. The toolbar
measures itself and updates as the grid resizes. The toolbar is one tab stop with roving focus:
ArrowLeft and ArrowRight move between items (mirrored in RTL), and Home and
End jump to the first and last item.

### Live demo: Toolbar

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

Built-in items (search, column chooser, expand and collapse all, export, print), built-ins with a custom label, custom items with reactive `disabled`, a centered custom `render` item, the overflow menu at a narrow width, `renderToolbar`, and `onToolbarItemClick` with `preventDefault()`.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridGrouping, type DataGridToolbarContext, type DataGridToolbarItem, type DataGridToolbarItemId } 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 columns: DataGridColumn<Order>[] = [
  { 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: 'priority', header: 'Priority', width: 100 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'note', header: 'Note', width: 220 },
];

const grouping: DataGridGrouping<Order> = { groupBy: ['country'], showDropArea: false, showGroupedColumns: true };

const narrowFrame = { maxWidth: 460 } as const;

// `renderToolbar` wraps the default toolbar with a heading.
function renderFramedToolbar({ defaultToolbar, items }: DataGridToolbarContext<Order>) {
  return (
    <div className="demo-toolbar-frame">
      <strong>Orders ({items.length} tools)</strong>
      {defaultToolbar}
    </div>
  );
}

export default function ToolbarDemo() {
  const [frozen, setFrozen] = useState(false);
  const [narrow, setNarrow] = useState(false);
  const [custom, setCustom] = useState(false);
  const [cancelPrint, setCancelPrint] = useState(true);
  const [editItems, setEditItems] = useState(false);
  const [log, push] = useEventLog();
  // Built-in ids, built-ins with overrides, and custom items. `disabled` is reactive.
  const toolbar: readonly (DataGridToolbarItemId | DataGridToolbarItem)[] = [
    // Edit items follow the edit state: select a row for Edit / Delete; while a row edits only Update / Cancel.
    ...(editItems ? (['add', 'edit', 'delete', 'save', 'cancel'] as const) : []),
    'expandAll',
    'collapseAll',
    { id: 'columnChooser', label: 'Columns', title: 'Show or hide columns' },
    'exportCsv',
    'exportExcel',
    'print',
    { id: 'refresh', label: 'Refresh', title: 'Reload the orders', disabled: frozen },
    { id: 'status', label: frozen ? 'Status: Frozen' : 'Status: Live', align: 'center', render: ({ disabled }) => <span className="demo-badge" data-tone={disabled ? undefined : 'success'}>{frozen ? 'Frozen' : 'Live'}</span>, disabled: frozen },
    'search',
  ];
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={frozen} onCheckedChange={(checked) => setFrozen(checked)}>
          Disable Refresh
        </Checkbox>
        <Checkbox checked={narrow} onCheckedChange={(checked) => setNarrow(checked)}>
          Narrow grid (overflow menu)
        </Checkbox>
        <Checkbox checked={custom} onCheckedChange={(checked) => setCustom(checked)}>
          Wrap with renderToolbar
        </Checkbox>
        <Checkbox checked={cancelPrint} onCheckedChange={(checked) => setCancelPrint(checked)}>
          Cancel the Print built-in
        </Checkbox>
        <Checkbox checked={editItems} onCheckedChange={(checked) => setEditItems(checked)}>
          Edit items (follow the edit state)
        </Checkbox>
      </div>
      {/* The toolbar renders beside the grid element, so the demo narrows their container. */}
      <div style={narrow ? narrowFrame : undefined}>
        <DataGrid<Order>
          // renderToolbar changes apply one render late (the toolbar reads synced props), so the demo remounts.
          key={`${custom ? 'framed' : 'plain'}-${editItems ? 'edit' : 'view'}`}
          aria-label="Orders with a toolbar"
          data={orders}
          columns={columns}
          toolbar={toolbar}
          search
          grouping={grouping}
          {...(editItems ? { editing: { mode: 'row' as const } } : {})}
          height={380}
          locale="en-US"
          currency="USD"
          timeZone="UTC"
          {...(custom ? { renderToolbar: renderFramedToolbar } : {})}
          onReady={(api: DataGridApi<Order>) => {
            // Export items stay disabled until a handler serves the command.
            api.registerCommandHandler('export.csv', () => {
              push('export.csv handler ran (an app would call exportCsv here)');
              return true;
            });
            api.registerCommandHandler('grid.print', () => {
              push('grid.print handler ran');
              return true;
            });
          }}
          onToolbarItemClick={(event) => {
            if (event.item.id === 'print' && cancelPrint) event.preventDefault();
            push(`toolbar (${event.source}): ${event.item.id}${event.defaultPrevented ? ' (built-in skipped)' : ''}`);
          }}
          onSearchChange={(event) => push(`search: "${event.text}"`)}
        />
      </div>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridToolbarItem`](https://salmonui.dev/docs/reference/data-grid/DataGridToolbarItem)
and [`DataGridToolbarItemId`](https://salmonui.dev/docs/reference/data-grid/DataGridToolbarItemId)
describe the items,
[`DataGridToolbarItemClickEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridToolbarItemClickEvent)
the click event, [`DataGridToolbarContext`](https://salmonui.dev/docs/reference/data-grid/DataGridToolbarContext)
the `renderToolbar` context, and
[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
`registerCommandHandler`.
