SpreadsheetGrid
Guides

Searchable select editor

Narrow options by typing with the select editor's search (also by reading or alias, options fetched from a server, filling other columns from the chosen option)

Write search: true on a select editor, and the cell itself becomes an input whose text narrows the list of options below it (since 1.7.0). In columns with dozens of options or more, such as customers, item codes or staff, users pick by typing a few characters instead of hunting with ↑↓. Even with thousands of options, the list draws only what's visible, so it stays fast. Select columns without search work as before.

Demo (order lines > pick customers and item codes by typing)

Warehouse requests: none yet
Rows 30 of 30Columns 7 of 7Sort: —
#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Rows 30 of 30Columns 7 of 7
Cell —Range —0 cells / 0 rows0 columns
  • Select a "Customer" cell and type "osa" to narrow to the companies in Osaka. Short codes are in searchText, so "trd" also finds the "… Trading" companies. Full-width and half-width, upper and lower case, and hiragana and katakana aren't distinguished.
  • "Item code" has 600 items. Typing "bolt" narrows by item name (the description note), and choosing an option fills "Item" and "Unit price" too (fillRow). "Undo" goes back to before the choice in one step.
  • "Owner" also accepts names not in the options (allowFreeText). Type and press Enter to write the text as is.
  • "Warehouse" fetches its options from a fake server when opened and on every keystroke (loadOptions; it waits 400ms). Turn on "Make loading warehouses fail" above, and the list shows "Retry".
  • Opening with double-click / Enter / F2 opens with the current value's name fully selected. Typing replaces it. Escape cancels.

Usage

import { SpreadsheetGrid, type GridColumn, type GridSelectEditorOption } from '@ishibashi0112/spreadsheet-grid';

const customers: GridSelectEditorOption[] = [
  // description is a faint note on the right of the list; searchText isn't shown but is used for searching (readings or aliases)
  { value: 'C-001', label: 'Tokyo Trading', description: 'C-001', searchText: 'tky trd' },
  { value: 'C-002', label: 'Osaka Industries', description: 'C-002', searchText: 'osa ind' },
  // ...
];

const columns: GridColumn<Order>[] = [
  {
    key: 'customer',
    title: 'Customer',
    width: 170,
    editable: true,
    editor: { type: 'select', options: customers, search: true },
    valueFormatter: ({ value }) => customers.find((option) => option.value === value)?.label ?? '',
  },
];

<SpreadsheetGrid rows={rows} onRowsChange={setRows} columns={columns} />;

Options have the same { value, label } shape as before, and you can add description / searchText / data (all optional. description is shown only in the searchable select editor's list, not in the list of a select without search). You can pass the same array to the column filter's options (filterOptions) as is (the column filter's search box looks only at label; it ignores searchText and kana variations).

Cells show the text of the column's valueFormatter (or the value itself if none); the grid doesn't show option names automatically (as with the select before). For columns whose values are codes, show the display name with valueFormatter as in the example above. If you group rows by it, also add groupLabel: 'formatted' so group rows show names too (Values and labels).

Create the options array outside the column definitions and reuse it (a per-row function should also return the same option objects). The text used for searching is kept per option object, so creating new options with items.map(...) on every render rebuilds all of it every time the editor opens (0.2–0.3 seconds each time for 50,000 options).

How it searches and orders

  • It shows options whose label / description / searchText / value contains the typed text.
  • Full-width and half-width, upper and lower case, hiragana and katakana, and spaces aren't distinguished ("ボルト", "ぼると" and "ボルト" are the same; "Osaka Trading" matches "Osaka Trading" too). The long vowel mark "ー" and hyphens, dashes and minus signs are all treated as - (typing "BLTーS" with the IME on still matches the item code "BLT-S"). The grid can't know how kanji are read, so put readings in searchText if you want users to search by them.
  • Options where one of them equals the typed text go first (type "A-100" and it goes above "A-1000" even if that comes earlier), then options that start with it, then options that contain it (each group in options order). The matched parts of label and description are bold.
  • It doesn't narrow during IME composition; it narrows when the text is committed.

Keys

KeyWhat happens
Printable keys / IME commitOpens with the list narrowed by the typed text (you can start typing with the cell selected. To start typing with the IME on, see imeDirectInput)
Double-click / Enter / F2Opens the list of all options with the current value's name fully selected (the current value is highlighted. If it isn't in the list, nothing is highlighted, and Enter without typing keeps the current value)
↑ / ↓ / PageUp / PageDownMove the highlight
EnterCommit the highlighted option and move down (follows editorEnterMove)
Tab / Shift+TabCommit the highlighted option and move right / left
EscapeCancel
Home / EndMove the cursor in the input

In options-only columns, typing highlights the first narrowed result. With no matching option, Enter / Tab do nothing (the list stays open; Escape cancels). When focus moves outside the grid, it cancels (as with the select before).

The pointer highlights the option you move onto. Even if the opened list lies under a mouse that isn't moving, the highlight doesn't change until the pointer moves (F2 → Enter keeps the current value). Options whose name or note is cut off show their full text on hover. Scrolling the cell being edited out of view hides the list, and scrolling back shows it again.

Allowing text not in the options (allowFreeText)

{
  key: 'owner',
  title: 'Owner',
  width: 130,
  editable: true,
  editor: { type: 'select', options: owners, allowFreeText: true }, // searching works even without writing search
}
  • While typing, no option is highlighted. Press ↓ to enter the list and choose. When no option matches the typed text, the list isn't shown.
  • Enter / Tab write the typed text when no option is highlighted (through the column's parseClipboardValue if any). If the typed text equals an option's name, it's the same as choosing that option.
  • When focus leaves, the typed text is written regardless of the highlight (options are chosen with Enter / Tab / a press).
  • Deleting all the text removes the highlight, and Enter / Tab write empty.

Fetching options from a server (loadOptions)

{
  key: 'warehouse',
  title: 'Warehouse',
  width: 160,
  editable: true,
  editor: {
    type: 'select',
    options: [], // used only to look up the current value's name (can be empty if unused)
    loadOptions: async ({ query, row, signal }) => {
      const response = await fetch(`/api/warehouses?q=${encodeURIComponent(query)}`, { signal });
      const items: { id: string; name: string }[] = await response.json();
      return items.map((item) => ({ value: item.id, label: item.name }));
    },
    // write the display name in the same single edit (a table that keeps the id as the value and the name in warehouseName)
    fillRow: (option) => ({ warehouseName: option.label }),
  },
  valueFormatter: ({ row }) => row?.warehouseName ?? '',
}
  • In this shape, where the name is kept in a row field (warehouseName), the value and name drift apart after paste, Delete and the fill handle, which don't call fillRow. To keep them aligned, write the name too in the column's setValue (which needs a way to look up the name), or look it up again from the rows the server returns ("Filling other columns from the chosen option" below).
  • It's called once when opened (with the typed starting text or empty text), then on every keystroke after waiting about 200ms. The argument is { query, row, rowKey, column, signal }.
  • Before calling with new text, and when the editor closes, the previous request's signal is aborted. Old responses that arrive anyway are discarded by the grid. Nothing is cached (cache inside loadOptions if you need to).
  • Filtering and order are exactly the returned array (the grid only adds the bold for matched parts).
  • While loading, the list shows "Loading options…"; on failure, "Couldn't load the options" with a "Retry" button (hover shows Error.message); with no match, "No matching options" (the texts are selectSearchLoading / selectSearchFailed / selectSearchNoMatch in localeText). After a failure, Enter also refetches the same text (options-only columns).
  • While refetching after retyping, the previous list is shown faded, and ↑ / ↓ and the pointer don't move the highlight (pressing to choose still works).
  • Pressing Enter / Tab while loading commits the first option of the list that arrives (typing an item code and pressing Enter right away doesn't commit an option from the old list). Text typed while waiting for the commit becomes the start of typing in the cell it moves to after committing (fast typing doesn't drop characters).
  • The text when the editor opens is the name of the current value's option if options has it, otherwise the column's valueFormatter text (options can be []).
  • In React StrictMode in development, it's called twice on open (the first is already aborted through signal).
  • In Next.js, loadOptions / fillRow are functions, so create the column definitions in a client component (pass the options array made on the server as props, and build the column definitions with useMemo). We recommend loadOptions calling a Route Handler with fetch(url, { signal }). Server Actions are processed one at a time and don't stop on signal, so fast typing delays results.

Filling other columns from the chosen option (fillRow)

// create the options once, outside the column definitions
const productOptions = products.map((product) => ({ value: product.code, label: product.code, description: product.name, data: product }));

{
  key: 'productCode',
  title: 'Item code',
  width: 120,
  editable: true,
  editor: {
    type: 'select',
    options: productOptions,
    search: true,
    fillRow: (option) => {
      const product = option.data as Product;
      return { productName: product.name, unitPrice: product.price };
    },
  },
},
{ key: 'productName', title: 'Item', width: 200, editable: false },
{ key: 'unitPrice', title: 'Unit price', width: 90, editable: false },
  • When you choose and commit an option, the fields fillRow returns are laid onto the same row. It's the same single edit as the chosen value, so onRowsChange is called once (one dataSource.updateRows with serverSide), and undo is one step.
  • Fields of read-only columns (editable: false / readOnly / canEditCell) are written too (for tables that look up the item name and unit price from the item code). Only fields whose value fails validation in validationMode: 'reject' columns aren't written.
  • Returned fields are written to the row as they are (not through the column's setValue). For the field of the column being edited, the chosen value wins. Fields equal to the current row's values aren't written (they're not in the write-back changes or the save marks either).
  • Fields not in any column can be written too. In serverSide's updateRows and the changes of onServerSideWriteError, they appear with the field name as columnKey.
  • It isn't called for commits that don't change the value (choosing the same option again), commits of typed text that differs from the option names (allowFreeText; text equal to a name counts as choosing the option, so it's called), paste, the fill handle or Delete. To align other fields on paste too, write them together in the column's setValue (setValue: (row, value) => ({ ...row, productCode: value, ...lookupProduct(value) })), or with serverSide, look them up again from the rows updateRows returns.
  • fillRow also works in select columns without search.

Paste, copy and the fill handle

  • Paste and copy are the same as the select before (raw values; with clipboard: 'label', names in options are read back). Options with the same name (differing only in description) can't be told apart when pasting, so if the pasted name equals the current value's name the current value stays; otherwise it becomes the first option with that name. Keeping names unique is the safe way.
  • Dragging the fill handle up or down copies the original value by default (since 1.7.0; advancing a trailing number in a code would give another option or a code not in the options). Drag while holding Ctrl / ⌘, or use the button after filling, to make a series.

Screen readers

The input is role="combobox" + aria-autocomplete="list", the list is role="listbox" and options are role="option". The highlighted option is pointed at with aria-activedescendant, and aria-setsize / aria-posinset convey the total and position (the list draws only what's visible). Loading and no-match notices are role="status", and failures are role="alert".

Keeping the bundle small

With /lite's createSpreadsheetGrid, add the feature part selectSearchFeature (about +4KB).

import { createSpreadsheetGrid, selectSearchFeature } from '@ishibashi0112/spreadsheet-grid/lite';

const Grid = createSpreadsheetGrid({ features: { selectSearch: selectSearchFeature } });

Without it, columns with search / loadOptions / allowFreeText open as the plain select (choose from the list only), with one warning in development. fillRow is in the core, so it works without the part.

Full details are in "Searchable select editor" in the API reference.

On this page