Editing
Editing a cell — free
The free DataGrid edits cells in place, and in the
other modes whole rows, forms and popups. Pass an editing
object — it is off without one:
import { DataGrid } from '@kanunilabs/datagrid-react';
<DataGrid
dataSource={rows}
rowKey="id"
columns={columns}
editing={{
// One call per committed cell, after the value is in the row.
onSave: async (changes) => {
for (const change of changes) await api.patch(change.rowKey, change.values);
},
}}
/>
Without React, the same option on createGrid:
import { createGrid } from '@kanunilabs/datagrid';
createGrid(host, {
dataSource: rows,
rowKey: 'id',
columns,
editing: { onSave: (changes) => api.save(changes) },
});
Double-click a cell, press F2, or just start typing on the
focused cell. Enter commits and moves down, Tab commits and moves to the
next editable cell, Esc cancels. The new value is written to the row, the
cellValueChanged event fires and onSave receives the change; a rejected
onSave is reported in the grid. Number and date columns get a number and a
date editor.
A column with editable: false stays read-only. So do columns with a lookup
or a renderEditor: those editors are part of Enterprise,
as are validation, adding and deleting rows, per-row permissions, undo and
redo, range selection, fill and paste. The five modes are free.
Parsing and writing values — free
The editors know a column's data type, not how your users write numbers.
valueParser turns what was typed into what the cell stores:
{
field: 'price',
headerName: 'Price',
// "€1,5" → 1.5
valueParser: ({ value, oldValue, row, columnId }) =>
Number(String(value).replace('€', '').replace(',', '.')),
}
It runs on every commit — and, in Enterprise, on every pasted cell, where it
gets the clipboard text — and before validation, so a rule checks 1.5, not
"1,5". Fill, undo and redo copy values that are already stored and do not run
it again.
valueSetter writes the value into the row yourself, for data the grid cannot
write by field — a nested object behind a valueGetter, or a store that must
not be mutated:
{
id: 'city',
headerName: 'City',
valueGetter: (row) => row.address.city,
valueSetter: ({ value, row }) => {
if (value === row.address.city) return false; // nothing changed
row.address = { ...row.address, city: String(value) };
},
}
Return false and the edit did not happen: no cellValueChanged, no onSave,
nothing to undo. Without a setter the grid writes row[field]. The setter is
called wherever the grid writes into your row — every commit in cell mode, and
in Enterprise also paste, fill, undo and redo. The buffered modes (batch,
row, form, popup) never write into the row; the change goes to your save
handler.
Modes — free
mode decides two things: what the user opens, and when the change is
persisted. All five modes work in the free DataGrid and createGrid; the
free grid starts in cell, EnterpriseDataGrid in batch.
| Mode | The user edits | Saved when |
|---|---|---|
cell (free default) | one cell | immediately on commit |
batch (Enterprise default) | any cells, freely | an explicit Save |
row | the whole row, in place | that row's Save |
form | the row as a form panel | that row's Save |
popup | the row as a modal dialog | that row's Save |
row, form and popup differ only in presentation — they share one row
session underneath, so Save, Cancel and validation behave identically in all
three. Switching between them mid-edit keeps what the user has typed.
In every mode except cell the grid does not write into your rows: the
changes wait until Save, go to onSave, and are then cleared. Write them
into your data there, or the cells go back to their old values:
const [rows, setRows] = useState(initialRows);
<DataGrid
dataSource={rows}
rowKey="id"
columns={columns}
editing={{
mode: 'batch',
onSave: async (changes) => {
await api.saveAll(changes); // throw to keep the changes pending
setRows((current) =>
current.map((row) => {
const change = changes.find((c) => c.rowKey === row.id);
return change ? { ...row, ...change.values } : row;
}),
);
},
}}
/>
In batch mode a Save / Cancel strip appears above the grid as soon as
something is pending.
Row, form and popup
Double-click a row to open it, or use Edit row… in the row context menu.
row turns every editable cell of that row into an editor and puts Save /
Cancel in the strip above the grid; form and popup lay the fields out with
labels and carry their own buttons.
// Free
editing={{ mode: 'popup', onSave: saveAndWriteBack }}
With Enterprise the same modes take validation rules, a new-row button and per-row handlers:
// Enterprise
editing={{
mode: 'popup',
allowAdding: true,
rules: {
product: [{ type: 'required' }, { type: 'stringLength', min: 3 }],
units: [{ type: 'required' }, { type: 'range', min: 1, max: 1000 }],
},
crud: {
update: (key, values, row) =>
fetch(`/api/orders/${key}`, { method: 'PATCH', body: JSON.stringify(values) })
.then((r) => r.json()),
},
}}
Four behaviours are deliberate:
Only that row is saved. A half-filled row elsewhere stays pending. That is
the whole difference from batch.
Nothing is written through until Save. The values live in the change store, so a Cancel genuinely restores the row and a cancelled edit never reached sorting, filtering or an export. Totals still follow the draft — the footer updates as you type, before you save.
A rejected save keeps the row open, holding what the user typed, with the server's message above the fields. Nothing is lost because row 3 of 10 hit a constraint.
Every field is validated on Save (Enterprise rules), not just the ones that were touched. A
required field the user never opened is the common failure on a new row, and
per-keystroke validation cannot see it. The first invalid field takes focus.
+ New row (Enterprise) in row/form/popup opens the new record instead of posting
a blank one; onInitNewRow seeds it, and Cancel removes it entirely.
Keyboard: Ctrl/⌘+Enter saves, Esc
cancels. In row mode a bare Enter also saves. In a form a bare
Enter is inert on purpose — in a grid it is one keystroke away at
all times, and "I pressed Enter and it saved a half-filled row" is the
complaint that follows.
Wording is translatable:
editing={{
mode: 'popup',
formLabels: { save: 'Kaydet', cancel: 'Vazgeç', editTitle: 'Satırı düzenle' },
}}
Row save status — free
For a grid that saves as the user goes, rowStatus marks each row with where
its save stands — a thin bar at the row's leading edge:
| Status | When | Colour |
|---|---|---|
changed | the row has edits not yet sent | --dg-row-status-changed (warning) |
saving | its save is on its way | --dg-row-status-saving (accent) |
saved | the save just succeeded — shown briefly | --dg-row-status-saved (success) |
error | the save was refused; stays until the row is edited or saved again | --dg-row-status-error (danger) |
<DataGrid
editing={{ onSave: (changes) => api.saveAll(changes) }}
rowStatus={{ tint: true, savedDuration: 2000 }}
…
/>
rowStatus: true turns on the marker; tint also washes the whole row in the
status colour, and savedDuration sets how long "saved" stays (milliseconds,
default 1500; 0 never shows it). The statuses come from the grid's own saves
in every mode. An app that saves outside onSave supplies its own with get,
and repaints by changing the data or calling controller.refreshCells():
rowStatus={{ get: ({ row }) => savingIds.has(row.id) ? 'saving' : undefined }}
Return undefined to fall back to the grid's status, null for none. Screen
readers hear the status too: the row carries it as a description, with
aria-busy while saving and aria-invalid on an error. The same option exists
on createGrid; the bar's width is --dg-row-status-width, the tint's
strength --dg-row-status-tint.
So that the status does not rest on colour alone, icons: true adds a narrow
column at the start with a glyph for each status: a dot while changed, a
turning ring while saving (still under "reduce motion"), a tick when saved, a
triangle when refused.
The reason under the row
messages: true puts a refused save's reason in a row right under it, with
Retry and, when you pass onDelete, Delete row:
<DataGrid
editing={{ onSave: (changes) => api.saveAll(changes) }}
rowStatus={{
icons: true,
messages: true,
// The grid does not delete: your app removes the row.
onDelete: ({ rowKey }) => setRows((rows) => rows.filter((r) => r.id !== rowKey)),
}}
…
/>
The reason is the message of the error your onSave threw. Retry sends
that row again. Delete row calls onDelete and leaves the deleting to your
app — on its server and in its data; the grid's own row deletion is part of
Enterprise.
Errors your app tracks itself go in errors, by row key; those rows read
'error', show their reason, and offer Retry when you pass onRetry:
rowStatus={{
messages: true,
errors: { 12: 'Locked by another user' },
onRetry: ({ rowKey }) => api.retry(rowKey),
}}
A reason in errors also replaces the grid's own for the same row — the place
to translate a server message. errors can be an object or a Map; after it
changes, repaint as for get.
Enterprise editing
Validation, adding and deleting rows, per-row permissions, per-row CRUD
handlers, lookup and custom editors, undo and redo, and range selection with
fill and paste are part of Enterprise. Import EnterpriseDataGrid instead of
DataGrid and pass an editing object:
import { EnterpriseDataGrid } from '@kanunilabs/datagrid-react-enterprise';
<EnterpriseDataGrid
licenseKey={key}
dataSource={rows}
rowKey="id"
columns={columns}
editing={{ mode: 'batch', allowAdding: true, allowDeleting: true }}
/>
Editing is ON by default in EnterpriseDataGrid, whether or not you pass
editing: with no prop at all, cells open an editor on double-click or typing,
and the cell menu offers Cut and Paste. The object configures editing; it does
not switch it on. For an Enterprise grid used for its other features — export,
charts, the status bar — and meant to be read-only, switch it off:
<EnterpriseDataGrid editing={{ enabled: false }} … />
That also turns off range selection, the fill handle and paste, which ride on editing (see range selection); copying stays.
Persistence
Two shapes, and the per-row one wins when both are present.
Per row (Enterprise) — one call per insert / update / delete, which is what a REST or SQL back end wants:
crud: {
insert: (values) => api.create(values), // return the stored row
update: (key, values, row) => api.patch(key, values),
remove: (key, row) => api.delete(key),
}
values on an update holds the changed columns only. Returning the stored
row makes the grid adopt the server's version of it — its real primary key,
defaults, computed columns. Return nothing and the grid leaves your data alone:
it never mutates your array behind your back.
As a batch (free) — one call with everything:
onSave: (changes) => api.saveAll(changes)
Either way a rejection fails the whole save and leaves the changes pending, so nothing the user typed is lost. The grid shows the reason in every mode — including cell mode, where each commit saves on its own and nobody else is waiting for the answer.
Supply a handler for every kind of change the grid allows. With crud
present and, say, allowAdding on but no insert, a save containing a new
row is refused before anything is sent, and the console names the missing
handler — rather than reporting the row as saved while it never reached you.
Validation — Enterprise
Rules are per column id, checked as the user types and again on save:
rules: {
email: [{ type: 'required' }, { type: 'pattern', pattern: /@/ }],
qty: [{ type: 'range', min: 1, max: 999 }],
code: [{ type: 'custom', validate: async (v) => (await isFree(v)) || 'Already taken' }],
}
Async rules run on save, not per keystroke.
Permissions — Enterprise
editing={{
allowAdding: true,
allowDeleting: (row) => row.status === 'draft',
allowUpdating: (row, columnId) => columnId !== 'id',
}}
A column the predicate refuses is read-only in every mode — it is skipped by Tab, shown but disabled in a form, and rejected by paste and fill.