Cell editing
Editor types (text / number / select / date / time / datetime / checkbox / custom), per-row editors, values with line breaks, where to move after committing, editing from code, and an overview of validation
Columns are editable by default (omitting editable = editable. To stop editing, use the column's editable: false or readOnly: true, readOnly for the whole grid, or canEditCell per cell). Choose the editor type with column.editor (unset = text). Validate values with column.validate, and choose what happens on failure with validationMode ('mark' = written but marked on screen / 'reject' = not written).
Columns with only getValue and no setValue (computed columns) are also editable by default; the committed value is just added to the row as row[key], and the display (getValue) doesn't change. Make computed columns editable: false, or write back to the source field with setValue (in development, a console.warn tells you once per column that added a property the row didn't have).
Demo
- Item — required check +
reject: trying to commit an empty value is refused by the editor (an error bubble shows). Clearing with Delete is skipped too. - Qty — the
numbereditor'smin: 0+integer: true(mark): negative numbers and decimals go in, but the cell gets a warning mark (a message such as "Enter 0 or more" when you hover or select the cell with the keyboard / a tap). Novalidateis written. - Type — the
selecteditor: choose with ↑↓ and commit with Enter. Typing printable keys does prefix type-ahead (names committed with an IME go to the options starting with those characters, or else containing them). For columns with many options,search: truelets users type to narrow them (Searchable select editor; since 1.7.0). - Due — the
dateeditor:Enter/F2/ double-click opens the browser's date input. Select a cell and start typing, as in2026/3/15, and it opens as a text input that reads the text as a date on commit (if it can't, it shows "Enter a date (e.g. 2026-03-15)" and keeps editing). - Active — the
checkboxeditor: press the checkbox itself or Space to toggle at once (no edit session. Pressing the cell outside the checkbox only makes it the active cell). - Note — a multiline
texteditor (multiline: true) +autoHeight:Alt+Enter(orCtrl/⌘+Enter) for a new line,Enterto commit. It's displayed with the value's line breaks and the row grows.
Editor types
const columns: GridColumn<Row>[] = [
{ key: 'name', title: 'Item', width: 190, editable: true }, // text (default)
{ key: 'qty', title: 'Qty', width: 120, editable: true,
editor: { type: 'number', min: 0, integer: true } }, // an integer of 0 or more (also validated)
{ key: 'category', title: 'Type', width: 140, editable: true,
editor: { type: 'select', options: [
{ label: 'Standard', value: 'standard' },
{ label: 'Custom', value: 'custom' },
] } },
{ key: 'dueDate', title: 'Due', width: 150, editable: true,
editor: { type: 'date' } },
{ key: 'active', title: 'Active', width: 110, editable: true,
editor: { type: 'checkbox' } },
]There are also time (type: 'time') and date-time (type: 'datetime') editors, and { type: 'date', picker: 'calendar' } to pick dates from a calendar (since 1.11.0; Time, date-time and calendar editors). With the select editor's multiple: true, any number of options can be chosen in one cell (since 1.11.0; Multi-select).
number / date / checkbox come with a default "text → value" parser that applies to paste, Delete clearing and editor commits alike (for example, clearing a number column with Delete gives null). Number columns also read full-width digits, signs and decimal points and thousands separators as numbers (pasting 1,234 or Excel's 1,234 gives 1234). Selecting a cell and starting to type with a minus sign or decimal point, as in -5 or .5, gives the number (-5 / 0.5) as is. An explicit parseClipboardValue always takes precedence.
For columns that receive pasted Excel currency or accounting format cells (¥12,000 / 12,000円 / (1,200)), pass the built-in number parser numberParser to parseClipboardValue. It reads the same way as the number column default (full-width and thousands separators too), removes the strip characters first, and with negativeParentheses reads numbers in parentheses as negative (since 1.1.0). Cells that a paste didn't write (cells that can't be edited, and values that failed validation in validationMode: 'reject' columns) are reported together once per paste through onPasteSkipped, so you can say something like "3 cells weren't written".
import { numberParser } from '@ishibashi0112/spreadsheet-grid';
{ key: 'amount', title: 'Amount', width: 120, editable: true,
editor: { type: 'number', min: 0 }, validationMode: 'reject',
parseClipboardValue: numberParser({ strip: ['¥', '¥', '円'], negativeParentheses: true }) }
<SpreadsheetGrid
onPasteSkipped={({ cells }) => toast(`${cells.length} cells weren't written (${cells[0]?.message ?? 'read-only cell'})`)}
/>For select columns whose value and display name differ (value 'transport' / display name "Travel"), writing clipboard: 'label' on the select editor makes copy and CSV use display names, and display names pasted from Excel are read back as values (values stay as is, and text that is neither stays raw; since 1.1.0). Show the display name in cells with valueFormatter (Values and labels).
const KINDS = [{ value: 'transport', label: 'Travel' }, { value: 'meal', label: 'Meetings' }];
{ key: 'kind', title: 'Type', width: 120, editable: true,
editor: { type: 'select', options: KINDS, clipboard: 'label' },
valueFormatter: ({ value }) => KINDS.find((o) => o.value === value)?.label ?? String(value ?? '') }For your own editing UI, use { type: 'custom', render: (ctx) => <MyEditor ... /> }. The element you return is drawn inside a transparent frame the same size as the cell being edited, so give its root element width: 100% / height: 100% and a background color (notes in the column API). Commit and cancel with ctx.commit(value) / ctx.cancel(). ctx.commit / ctx.cancel of an earlier edit called after that edit ended (after a commit / cancel / editing another cell) does nothing (ctx.commit returns { status: 'noop' }). Built-in editors commit when they lose focus. Custom editors should also call ctx.commit(value) (or ctx.cancel()) in the input's onBlur. Pressing another cell, a row number or a column header in the grid (also the header corner, row grips, detail toggles and empty space in the table) while the editor is open makes the grid end the edit and close the editor (the pressed cell becomes active and keys keep working). Pressing inside the cell being edited where the editor's parts don't cover doesn't close it. If onBlur calls ctx.commit, that value is written to the cell that was being edited; otherwise the unfinished input isn't written. Even an editor that waits for a server check in onBlur before calling ctx.commit gets the value written to the cell that was being edited when it arrives after the editor closed (the active cell stays on the pressed cell). However, it isn't written while the same cell has been opened again for editing before the value arrives, after the grid was unmounted, or when validation rejects the value (ctx.commit returns { status: 'rejected' }. The editor is already closed, so show any notice from your side). Up to 1.4.0, editors that didn't commit in onBlur stayed open, and the grid's keys didn't work until another cell was double-clicked. While the same edit continues, the component from render(ctx) isn't recreated (since 1.3.0; also when rows are added above). When editing starts by typing a letter key, that key is in ctx.initialText, so use it as the input's initial value. When opened by double-click / Enter / F2, ctx.initialText is the text of the cell's value (String(value ?? '')) (to use it only when typing started editing, tell them apart with ctx.initialText !== String(ctx.value ?? '')). When using the grid's imeDirectInput, adding imeDirectInput: true to the editor definition puts text committed with an IME into ctx.initialText too (since 1.2.0; Keyboard and touch).
Per-row editors (editorForRow)
With the column's editorForRow, the editor can change per row within the same column (since 1.11.0). It's for tables like a list of settings, where the value type differs by kind of item.
- There is only one "Value" column; the daily limit row opens an integer from 0 to 100, the intake status row a select, the notify row a checkbox, the cutoff time row a time, and the note row text.
- Paste,
Deleteand built-in validation are also decided by the row's editor (pastingabcinto the daily limit row marks it, andDeletein the notify row givesfalse).
import type { GridColumn, GridColumnEditor } from '@ishibashi0112/spreadsheet-grid';
const EDITORS: Record<Setting['kind'], GridColumnEditor<Setting> | undefined> = {
number: { type: 'number', min: 0, max: 100, integer: true },
status: { type: 'select', options: STATUS_OPTIONS },
flag: { type: 'checkbox' },
time: { type: 'time', step: 30 },
note: undefined, // the column's editor (text here)
};
const columns: GridColumn<Setting>[] = [
{ key: 'name', title: 'Setting', width: 170, editable: false },
{ key: 'value', title: 'Value', width: 160, editable: true, editor: { type: 'text' }, editorForRow: (row) => EDITORS[row.kind] },
];- The returned editor wins over
editor. Rows that returnundefineduse the column'seditor(text if none). - Places without a row (the guess of a column filter's
filterType: 'auto', condition summaries,/ai, the column forfocusNewRow()) use the column'seditor. To decide the kind of column filter, writefilterType. - The function is called many times during rendering, so keep it pure and light (just look up a constant table, as above).
- If a row changes from outside during an edit and the editor type changes (a number row becomes a checkbox row, for example), the edit is cancelled.
- To see per-row editors in your own code (inside
renderCelland so on), writecolumn.editorForRow?.(row) ?? column.editor(the type ofeditoris the same as before and doesn't hold functions).
Values with line breaks (multiline)
The default text editor is a single-line input, and the browser removes line breaks (open a value with line breaks, edit it, and the line breaks are gone on commit). For columns with line breaks in their values, editor: { type: 'text', multiline: true } edits in a multiline input. The input grows downward with its content, stops at the bottom of the table's visible area, and scrolls inside.
{ key: 'note', title: 'Note', width: 240, autoHeight: true,
editor: { type: 'text', multiline: true } } // Enter commits, Alt+Enter adds a line break (as in Excel)
{ key: 'body', title: 'Body', width: 320, autoHeight: true,
editor: { type: 'text', multiline: true, enterKey: 'newline' } } // Enter adds a line break, Ctrl / ⌘+Enter commitsenterKey | Enter | Line break | Commit |
|---|---|---|---|
'commit' (default; as in Excel) | Commit and move down | Alt+Enter / Ctrl+Enter / ⌘+Enter | Enter / Tab |
'newline' (closer to a notepad or chat) | Line break | Enter / Shift+Enter / Alt+Enter | Ctrl+Enter / ⌘+Enter / Tab |
In both, Tab commits and moves right, Escape cancels, and losing focus commits. Soft keyboards on phones can't press Alt / Ctrl, so the default 'commit' can't add line breaks there. For columns where mobile users need line breaks, use enterKey: 'newline' (commit by tapping outside = losing focus). Line breaks are displayed only in autoHeight columns (wrapped at the value's line breaks, and the row grows); other columns show it on one line.
Unmounting the grid while editing
Built-in editors commit when they lose focus. Unmounting the whole grid during an edit (switching screen tabs with a keyboard shortcut, for example) causes no focus loss, so the typed value is discarded (hiding with display: none or pressing a tab with the mouse commits through focus loss). To commit before unmounting, call blur() on the input at the start of your unmount logic. The grid calls onRowsChange before it goes.
const switchTab = (next: string) => {
// commit the value being edited before unmounting
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
setTab(next);
};Where to move after Enter commits (editorEnterMove)
After Enter commits a built-in editor, the active cell moves one row down by default (as in Excel). Change it with the editorEnterMove prop:
<SpreadsheetGrid editorEnterMove="none" ... /> // 'down' (default) | 'up' | 'right' | 'left' | 'none''none' stays in place without moving. Label rows (labelRow) aren't stops; it moves on to the next data row in the same direction (if only label rows lie ahead, it stays on the committed row). It doesn't affect Tab / Shift+Tab (right / left). Custom editors pass the direction as the second argument of ctx.commit(value, direction) (not covered by this prop).
The destination is clamped by the row count "after the re-render that applies the commit", so in entry grids that add an empty row at the end in onRowsChange (the standard paste + direct entry pattern), committing the last row with Enter moves straight into the added row.
Starting an edit from code / returning focus
To edit a row added with an "Add row" button right away, use the imperative API's startEditing(viewRowIndex, colIndex) (the same as F2. It selects the cell, scrolls it into view and moves focus to the editor). Positions are view positions, so while sorted or filtered, look up the row with getViewRowIndex(rowKey) from its row key rather than rows.findIndex, and the column with getColIndex(columnKey).
import { flushSync } from 'react-dom';
const addRow = () => {
const row = { id: crypto.randomUUID(), name: '' };
flushSync(() => setRows((prev) => [...prev, row])); // look it up after the grid knows the new row
const grid = gridRef.current;
const viewRowIndex = grid?.getViewRowIndex(row.id) ?? -1;
const colIndex = grid?.getColIndex('name') ?? -1;
if (viewRowIndex >= 0 && colIndex >= 0) grid?.startEditing(viewRowIndex, colIndex);
};When keys stop reaching the grid, as after closing a modal opened from the context menu, focus() returns focus to the grid (to the input catcher when imeDirectInput is on). Details are in Imperative API.
Making outside changes undoable too
Replacing rows from a button outside the grid ("Delete the selected rows" and so on) clears the undo history (the grid doesn't know about changes made outside it). For changes you want undoable, pass them through the imperative API's applyRows(nextRows) instead of setRows. It records them in the history before passing them to onRowsChange, so Ctrl/Cmd+Z reverts them.
const deleteSelected = () => {
const keys = new Set(gridRef.current?.getSelectedRowKeys() ?? []);
gridRef.current?.applyRows(rows.filter((row) => !keys.has(row.id)));
};When the row being edited moves or disappears
When the row being edited moves through sorting or rows added above, the editor follows it (the unfinished input stays, and custom editors aren't recreated). When the row leaves the filter (it's still in rows; a "Today" filter when the date changes, for example), the unfinished input is committed and written to that row, and focus stays in the grid (since 1.3.0).
- text / number / date editors write the unfinished input. Custom editors write the value if the input's
onBlurcallsctx.commit(when filtering shrinks the table and no row remains at the editing position, the editor may be removed beforeonBlurand nothing is written); select cancels. - Rows that can't be written (
canEditCellisfalse; the position passed is the one before it left) and values validation rejects aren't written. - When
rowsis replaced by other rows and the row being edited is gone (looked up by row key), and with serverSide, the edit is cancelled.
Up to 1.2.x, the edit ended silently (the unfinished input was discarded), and focus fell to the page's body, where keys didn't work.
Tables that change from outside all the time (live updates)
For tables whose rows change from outside all the time, like stock prices or inventory, pass updates with applyRows(next, { undoable: false }) (since 1.1.0). They aren't recorded in the history and the current history isn't cleared, so when a user reverts a note they edited with Ctrl/Cmd+Z, only the note goes back while the later price updates stay (redo works the same). Rebuilding rows and passing it with setRows clears the history, and passing it with applyRows without undoable records every update in the history so Ctrl/Cmd+Z rewinds the prices.
applyRows also accepts a function ((prev) => next). prev is the rows last passed, so the feed callback doesn't need to keep the latest rows in a ref. Rows are matched with rowKeyGetter, so write rowKeyGetter for tables where rows are added and removed (without it, when the row count changes or row keys collide, the row from before the edit is restored as in 1.0, so outside updates are reverted too).
useEffect(() => {
const unsubscribe = feed.subscribe((prices) => {
gridRef.current?.applyRows(
(prev) => prev.map((row) => (prices[row.symbol] === undefined ? row : { ...row, price: prices[row.symbol] })),
{ undoable: false },
);
});
return unsubscribe;
}, []);
<SpreadsheetGrid ref={gridRef} rows={rows} onRowsChange={setRows} rowKeyGetter={(row) => row.symbol} columns={columns} />In tables whose values change while sorted (a stock board sorted by largest daily change, for example), the active cell stays at its view position (which row number) by default, so it points at a different stock every time they swap places (as in Excel). To make it follow the pressed stock, write activeCellFollows="row" (since 1.2.0).
A stock board sorted by the largest change. Every second three stocks change and the order shifts. Click a stock’s cell and compare how the active cell moves with "position" and "row" (the "Active cell" above is what onActiveCellChange received; with row it is not called when only the stock moves).
<SpreadsheetGrid activeCellFollows="row" rowKeyGetter={(row) => row.symbol} /* ... */ />- A range over several columns of the same row moves with it; a range spanning several rows is cleared to the single active cell when the stocks inside it change places (stocks the user didn't mean to select would go into copies and aggregates; the same applies even if the active cell's stock doesn't move). Ranges spanning all rows (
Ctrl+Aand so on) and column selections stay as they are. - The table doesn't scroll. If the cell moves off screen, pressing an arrow key moves to it.
- When the followed row disappears or is hidden by a filter, the cell stays at its position. It doesn't move while dragging a selection, and follows on release.
- To follow through rows being added / removed too, write
rowKeyGetter(without it, row keys are positions inrows, so removing a row above makes the same key point at another row). onActiveCellChangeisn't called when only the position moves (only when the cell itself moves).- Only for tables given
rows(clientSide). With serverSide, sorting happens on the server and the order doesn't change until refetched, so the cell stays at its position. A cell being edited follows its row even by default. - When you edit and commit the sort column and that row moves,
Entergoes to the row that was below in the order before the commit, andTabgoes to the next cell of the edited row (so the row you keep entering doesn't jump). With the default'position', it goes below / beside that position in the order after the commit.
Validation
{
key: 'name', title: 'Item', width: 190, editable: true,
validate: ({ value }) => String(value ?? '').trim() !== '' || 'Item is required',
validationMode: 'reject', // default is 'mark'
}'mark'(default) — the value is written, and the cell shows a mark (background + triangle at the top right + message).'reject'— the write itself is stopped. An editor commit is "stopped, editing continues, and an error bubble shows"; paste / clear / the fill handle skip only the cells that fail.- The number editor's
min/max/integer: truework as value validation as they are, without writingvalidate.
showValidationMarks to decide when marks appear, getInvalidCells() to check everything before saving, message language and more are in Validation.
Troubleshooting
Common questions (the table doesn't show, edits don't stick, undo is lost, pasted values don't go in, menus can't be pressed inside dialogs or Shadow DOM, 500 on Next.js and more) and known limitations
Entry row
Show an entry row at the end of the table with newRow and add typed rows to the end. Drafts, when it becomes a row, paste, and tracking added and removed rows