# Lookup columns

> Foreign-key columns that store a key and show, sort, filter, search and group by a looked-up value, from a local table or a cached remote source.

Canonical: https://salmonui.dev/docs/data-grid/lookup-columns

A lookup column (a foreign-key column) holds a key in the row and
displays a value from another table:

```tsx
const customers = [{ id: 1, name: 'Aiko Tan' }, { id: 2, name: 'Bao Nguyen' }];

const columns: DataGridColumn<Order>[] = [
  { field: 'customerId', header: 'Customer', lookup: { data: customers, keyField: 'id', displayField: 'name' } },
];
```

`keyField` is the field of the lookup rows matched against the cell value
(default: the column `field`); `displayField` is the field shown. Both accept
dot paths. All lookup settings live in `column.lookup`. The React `DataGrid` registers the lookup module automatically as soon
as a column declares `lookup`; there is nothing to import or inject.

The display text is what the user sees, so it is also what the grid works
with: sorting orders by the name, not the key; the filter row, the
filter menus, checkbox facets and search match the name; and
grouping groups by the name. The row itself keeps the key, so
`api.getViewRows()` returns rows with the raw value. The display text feeds
the dictionary-encoded sort keys, so a warm re-sort or re-filter of a lookup
column runs no lookups.

To list the lookup columns, filter the compiled columns: those
returned by `api.getColumns()` carry `lookup` on lookup columns, so
`api.getColumns().filter((c) => c.lookup)` returns them. A dedicated method
would grow the API without adding a capability.

Export (CSV, Excel, PDF) and the clipboard module's `copy()` write the
display text, never the key; an unknown key, or a remote key still
loading, exports blank. Pasting either the key or the display text
into a lookup cell stores the key ([Clipboard](https://salmonui.dev/docs/data-grid/clipboard)). Copying
an edited lookup cell copies the display text of its draft key.

### Live demo: Lookup columns

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

Two local lookup (foreign-key) columns - cells hold keys and show names; sorting, filtering, search and grouping run on the display text; the lookup columns are listed from api.getColumns().

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridSorting } from '@salmonui/data-grid';
import { createOrders } from '../../lib/fixtures';

// Lookup tables: the order rows hold keys, the grid shows the names.
const customers = [
  { id: 1, name: 'Aiko Tan' },
  { id: 2, name: 'Bao Nguyen' },
  { id: 3, name: 'Chen Wei' },
  { id: 4, name: 'Dewi Lestari' },
  { id: 5, name: 'Elif Kaya' },
  { id: 6, name: 'Farah Aziz' },
  { id: 7, name: 'Goran Petrov' },
  { id: 8, name: 'Hana Sato' },
];
// Key order (D1..D5) differs from display order: sorting and grouping follow the titles.
const departments = [
  { code: 'D1', title: 'Operations' },
  { code: 'D2', title: 'Finance' },
  { code: 'D3', title: 'Marketing' },
  { code: 'D4', title: 'Engineering' },
  { code: 'D5', title: 'Human resources' },
];

interface OrderRow {
  readonly id: string;
  readonly customerId: number;
  readonly department: string;
  readonly product: string;
  readonly amount: number;
}

// Deterministic keys (no Math.random): identical server and client markup.
const rows: OrderRow[] = createOrders(2_000, 5).map((order, index) => ({
  id: order.id,
  customerId: (customers[(index * 7) % customers.length] as { id: number }).id,
  department: (departments[(index * 3) % departments.length] as { code: string }).code,
  product: order.product,
  amount: order.amount,
}));

const columns: DataGridColumn<OrderRow>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  // The cell value is the key; the grid displays, sorts, filters, searches and groups by `displayField`.
  { field: 'customerId', header: 'Customer', width: 160, lookup: { data: customers, keyField: 'id', displayField: 'name' } },
  // `keyField` defaults to the column field when the lookup rows use the same name; here it is `code`.
  { field: 'department', header: 'Department', width: 170, lookup: { data: departments, keyField: 'code', displayField: 'title' } },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

// Sorted by the display text: "Aiko Tan" first, although its key is 1 of 8.
const sorting: DataGridSorting = { multiple: true, sortBy: [{ field: 'customerId', direction: 'asc' }] };

export default function LookupColumnsDemo() {
  const api = useRef<DataGridApi<OrderRow> | null>(null);
  const [status, setStatus] = useState('Type "fin" in the Department filter cell and press Enter: the filter matches the display text.');
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.groupColumn('department')}>
          Group by Department
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearGrouping()}>
          Clear grouping
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            // The compiled columns that carry `lookup`.
            const lookups = (api.current?.getColumns() ?? []).filter((column) => column.lookup);
            setStatus(`Lookup columns: ${lookups.map((column) => `${column.headerText} (${column.lookup?.keyField} -> ${column.lookup?.displayField})`).join(', ')}`);
          }}
        >
          List lookup columns
        </Button>
        <Button variant="outline" onClick={() => api.current?.filterColumn('department', 'contains', 'fin')}>
          Filter Department contains &quot;fin&quot;
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearFiltering()}>
          Clear filters
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            const first = api.current?.getViewRows()[0];
            if (first) setStatus(`First row ${first.id}: the row stores customerId ${first.customerId} and department ${first.department}; the cells show the names.`);
          }}
        >
          Show the stored keys
        </Button>
      </div>
      <DataGrid<OrderRow>
        aria-label="Orders with lookup columns"
        data={rows}
        columns={columns}
        sorting={sorting}
        filtering
        search
        toolbar={['search']}
        grouping
        height={380}
        locale="en-US"
        currency="USD"
        ref={api}
      />
      <p className="demo-status" aria-live="polite">
        {status}
      </p>
    </>
  );
}
```

## Server-side sources

The display-text ordering above is what the grid does when it holds the
rows (a local array or an offline source). With a server-side source (for
example `createJsonDataSource`), sorting and grouping run on the server, and
the grid sends a lookup column like any other column: by its `field`, which
holds the key (through `fieldOf` when set). Sorting the `customerId` lookup
column sends `sort: [{ field: 'customerId', dir: 'asc' }]`, and grouping by it
sends `group: [{ field: 'customerId' }]`; the lookup table never travels with
the query.

A server that sorts the raw key orders the rows by key, not by name. To
order by the display text, as the grid does locally, the server joins the
lookup table and sorts by the display value; for grouping it orders
the groups by the display value and keeps the key as the group key, which the
grid shows through the lookup. The reference handler does this join
when told which fields hold lookup keys:

```ts
import { createJsonQueryHandler } from '@salmonui/data/server';

createJsonQueryHandler(orders, {
  key: 'id',
  lookups: { customers },
  lookupFields: { customerId: { lookup: 'customers', keyField: 'id', displayField: 'name' } },
});
```

A SQL backend does the same with a join (`ORDER BY customers.name,
orders.customer_id`).

## Remote lookups

`lookup.data` can also be a `LookupSource`, an object with
`load({ keys, keyField, displayField, signal })` that returns the lookup rows
of the requested keys. The grid asks only for the keys it needs,
batched per microtask, and re-sorts or re-filters when they arrive.
`@salmonui/data/lookup` ships two cached sources:

- `createLookup({ load, keyField?, ttl? })` wraps any loader with a per-key
  cache: cached and known-missing keys never reach the loader, identical
  in-flight keys are joined, and entries expire after `ttl` ms.
- `createJsonLookup({ url, name, ttl? })` loads over the JSON protocol
  endpoint (`createJsonQueryHandler(rows, { lookups: { [name]: rows } })` on
  the server).

One lookup can back several columns and several grids. While a remote lookup
column is loading, its header carries `data-lookup-status="loading"` and
`aria-busy="true"` with a status indicator labelled by the `lookupLoading`
text; a failed load shows `data-lookup-status="error"` (`lookupError`).
Remote lookups display as strings.

### Live demo: Remote lookup

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

A lookup column backed by a cached @salmonui/data createLookup source with a simulated 900 ms server; the missing keys load in one batched request while the header shows the load status.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createLookup, type CachedLookup } from '@salmonui/data/lookup';
import { DataGrid, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders } from '../../lib/fixtures';

// The "server" side of the lookup: a table the browser does not hold.
const SUPPLIERS: Readonly<Record<number, string>> = {
  101: 'Andes Roasters',
  102: 'Blue Ridge Tea Co.',
  103: 'Copperline Equipment',
  104: 'Darjeeling Direct',
  105: 'Ember & Steel',
  106: 'Fjord Beans',
};
const supplierIds = Object.keys(SUPPLIERS).map(Number);

interface OrderRow {
  readonly id: string;
  readonly supplierId: number;
  readonly product: string;
  readonly amount: number;
}

const rows: OrderRow[] = createOrders(500, 13).map((order, index) => ({
  id: order.id,
  supplierId: supplierIds[(index * 5) % supplierIds.length] as number,
  product: order.product,
  amount: order.amount,
}));

const wait = (ms: number, signal: { readonly aborted: boolean }) =>
  new Promise<void>((resolve, reject) => {
    setTimeout(() => (signal.aborted ? reject(new Error('aborted')) : resolve()), ms);
  });

export default function LookupRemoteDemo() {
  const [log, push] = useEventLog();
  // One cached lookup per demo instance; the grid asks it for the keys it shows.
  const [suppliers] = useState<CachedLookup>(() =>
    createLookup({
      async load({ keys, signal }) {
        push(`load: ${keys.length} key(s) requested (${keys.join(', ')})`);
        await wait(900, signal);
        return keys.map((key) => ({ id: key, name: SUPPLIERS[Number(key)] ?? `Unknown supplier ${String(key)}` }));
      },
    }),
  );
  const [columns] = useState<DataGridColumn<OrderRow>[]>(() => [
    { field: 'id', header: 'Order', primaryKey: true, width: 110 },
    // A remote lookup: `data` is a LookupSource. The header shows a loading indicator until the names arrive.
    { field: 'supplierId', header: 'Supplier', width: 200, lookup: { data: suppliers, keyField: 'id', displayField: 'name' } },
    { field: 'product', header: 'Product', width: 150 },
    { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  ]);
  return (
    <>
      <DataGrid<OrderRow>
        aria-label="Orders with a remote lookup column"
        data={rows}
        columns={columns}
        sorting
        filtering
        height={320}
        locale="en-US"
        currency="USD"
      />
      <EventLog entries={log} label="Lookup requests" />
    </>
  );
}
```

## API reference

[`ColumnLookup`](https://salmonui.dev/docs/reference/data-grid/engine/ColumnLookup) lists the
`lookup` options and [`LookupSource`](https://salmonui.dev/docs/reference/data-grid/engine/LookupSource)
the remote contract; [`createLookup`](https://salmonui.dev/docs/reference/data/lookup/createLookup),
[`createJsonLookup`](https://salmonui.dev/docs/reference/data/lookup/createJsonLookup) and
[`createJsonQueryHandler`](https://salmonui.dev/docs/reference/data/server/createJsonQueryHandler)
cover the cached sources and the server join.
