gridcn2.0.0
Editing cells

Lookup cell

Add a cell type whose options come from a server and are searched as the user types.

A select column takes a fixed list of choices. A foreign-key column can have thousands of options, so it needs a search. The lookup cell type calls your fetchOptions function while the user types. It stores the picked key together with its label.

Item
Customer
Anvil
Acme North
Rocket skates
Giant magnet
wonka-2
pnpm dlx shadcn@latest add @gridcn/data-grid-lookup

Register the type and give the column its options:

import {
  lookupCellType,
  type LookupOption,
  type LookupOptions,
  type LookupValue,
} from "@/components/data-grid-lookup/data-grid-lookup";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";

type Order = { id: string; customer: LookupValue };
type Customer = { id: string; name: string };

const customerOptions: LookupOptions<Order> = {
  fetchOptions: async ({ query, signal }) => {
    const url = `/api/customers?q=${encodeURIComponent(query)}`;
    const res = await fetch(url, { signal });
    const customers = (await res.json()) as Customer[];
    return customers.map(
      (c): LookupOption => ({ value: c.id, label: c.name }),
    );
  },
};

const columns = defineColumns<Order>()([
  {
    id: "customer",
    header: "Customer",
    accessorKey: "customer",
    type: "lookup",
    options: customerOptions,
  },
]);

export function Orders({ orders }: { orders: Order[] }) {
  return (
    <DataGrid
      defaultData={orders}
      cellTypes={{ lookup: lookupCellType }}
      columns={columns}
    />
  );
}

Each lookup column of a grid remembers the labels that its editor listed and its cells showed. An inline fetchOptions keeps them. To drop them, for example after fetchOptions switches to another source, change labelCacheKey.

The stored value

A cell holds { value, label } or null. value is the key your server uses. label is the text the grid shows, copies, sorts, searches, and filters.

A row can also hold a bare key, for example "c9". The cell shows a bare key in muted text with a data-unresolved attribute until the user picks an option. A stored value with an empty label, for example from unresolvedPaste: "keep", shows the same way. A fetched option with an empty label shows its key.

Editing

Press Enter, F2, or Space, or double-click the cell, to open the editor. Typing a character opens it with that character in the search box.

KeyAction
TypeSearch after the pause set by debounceMs.
ArrowDown, ArrowUpMove through the options.
EnterPick the active option. While typing is pending, Enter searches first.
EscapeClose the editor and keep the old value.
Delete (cell not in edit)Clear the cell.

A click on an option picks it. If minQueryLength is 0, the editor opens with the default list. An IME composition searches when it ends. Enter and Escape during a composition act on the composition, not on the cell.

A new request aborts the one before it through signal. The editor drops a late answer of an older query. A failed request shows an error line with a Retry button. A grid with readOnly opens no editor.

Options

OptionEffectDefault
fetchOptionsResolves { value, label }[] for { query, signal, row, rowId, columnId }.required
debounceMsWait after the last keystroke before a request starts.the inputDebounceMs of the grid
minQueryLengthFewest typed characters that start a request.0
maxResultsMost options shown. The limit is 200.50
unresolvedPasteA pasted text that matches no known option keeps the cell value and reaches onValidationError. With "clear", it empties the cell. With "keep", the grid stores { value: text, label: "" } with the pasted text trimmed, and shows it as unresolved."reject"
resolveLabelsResolves the pasted labels that no option, cell, or copy has shown. A paste calls it once with the distinct unknown labels and holds the paste until it answers.none
labelCacheKeyThe grid forgets the remembered labels of the column when this value changes.none
labelsText for searching, noResults, error, retry, and typeMore.English

Lookup options lists every option, the request fields, and the label defaults.

The answer is untrusted. The editor keeps only entries with a non-empty value (text or a finite number, stored as text) and a text label. It drops a repeated value, cuts both at 256 characters, and keeps the first maxResults. It renders labels as text.

Dependent lookups

fetchOptions receives the row that the user edits. Type the options with your row type and read the row to narrow the options, such as the cities of the country in that row:

import type {
  LookupOption,
  LookupOptions,
  LookupValue,
} from "@/components/data-grid-lookup/data-grid-lookup";

type Address = { id: string; country: string; city: LookupValue };

async function searchCities(
  query: string,
  country: string,
  signal: AbortSignal,
): Promise<LookupOption[]> {
  const params = new URLSearchParams({ q: query, country });
  const res = await fetch(`/api/cities?${params}`, { signal });
  return (await res.json()) as LookupOption[];
}

export const cityOptions: LookupOptions<Address> = {
  fetchOptions: ({ query, row, signal }) =>
    searchCities(query, row.country, signal),
};

Clipboard, fill, import, and export

  • Copy and export write the label.
  • A pasted or imported label resolves when the grid showed it. The grid shows labels in the editor list and in cells. It also writes them for copy, export, print, a fill source, autosize, and the filter value list. The grid remembers up to 5,000 labels for each lookup column, and the oldest leave first.
  • With resolveLabels, a paste first asks it for the labels that the grid does not know. The paste is held as the resolveTexts gate, so useDataGridGatePending and gateTimeoutMs cover it. The call gets the signal of the paste. A rejected call cancels the paste.
  • Other text follows unresolvedPaste. By default, it keeps the cell value and reaches onValidationError. A label that no cell, editor, or copy has shown follows unresolvedPaste too, so a paste from another spreadsheet keeps the cell value by default.
  • A fill inside the lookup column follows this table:
FillResult
Plain fillCopies the stored { value, label }, also a bare key and a label that two options share.
Series of labels that all resolveResolves each label like a paste.
Vertical series with a label that resolves to no optionCopies the stored values.
Horizontal series with a label that resolves to no optionRepeats the source text of that row.

With unresolvedPaste: "keep", every label resolves. A series then stores each new label as { value: "Store 3", label: "" }. A fill into another lookup column resolves each label like a paste into that column.

Clear and Delete store null.

Sort, search, and filter

Sort, quick search, and the text filter operators use the label. The set operators isAnyOf and isNoneOf match the stored key or the label.

Server mode

The cell calls your fetchOptions in every data mode, because the options live on your server and not in the grid rows. It receives { query, signal, row, rowId, columnId } and resolves { value, label }[]. A text operator on a lookup column sends the label text, so the server compares labels. A set filter sends the entries of its list. Fill the list with fetchFilterValues and return the key as value, so the server compares keys. Local data, pagination, scroll mode, and a server-sorted grid all use the same column definition.

Types

  • LookupOption is { value, label }.
  • LookupValue is the stored value: a LookupOption, a bare key string without a label, or null.
  • LookupFetchRequest<TData> is the argument of fetchOptions: query, signal, and the edited row, rowId, and columnId. TData is your row type and defaults to unknown.
  • LookupOptions<TData> takes the same row type.
  • LookupResolveRequest is the argument of resolveLabels: labels and signal.
  • LookupLabels holds the strings of the editor: searching, noResults, error, retry, and typeMore.

Type the column with defineColumns. accessorKey takes LookupValue, and options takes LookupOptions<Row>.

On this page