Features
Most of this page is in the free Community package. The sections marked
Enterprise need EnterpriseDataGrid (React) or createEnterpriseGrid
(JavaScript): merged cells, cell notes, Excel and PDF export, multi-level
grouping with group summaries, and the chart panel. In the Community grid
those options are ignored (debugMode says so), and exportToExcel /
exportToPdf throw an error that names the Enterprise package. CSV export is
Community.
Data
An array is the simple case:
<DataGrid dataSource={rows} rowKey="id" />
For data that lives on a server, pass a DataSource — an object with a
load(options) method. The grid hands it skip, take, sort, filter,
searchText and (when grouping remotely) group/groupKeys, and expects
{ rows, totalCount } back. createRestDataSource is that object for an HTTP
endpoint:
import { createRestDataSource } from '@kanunilabs/datagrid-react';
const source = createRestDataSource<Order>({ url: '/api/orders' });
<DataGrid dataSource={source} rowKey="id" />
It handles three things that are easy to get wrong by hand. Every load
aborts the one before it, so typing in the search box cannot leave the grid
showing the results of an earlier query. sort and filter are JSON-encoded
rather than stringified, which is what URLSearchParams would otherwise turn
into [object Object]. And a non-2xx response throws, because fetch
resolves on a 500 and the grid would otherwise try to render an error page as
rows.
Adapt it to an existing API without giving up any of that:
createRestDataSource<Order>({
url: '/odata/Orders',
headers: () => ({ Authorization: `Bearer ${getToken()}` }),
buildQuery: (o) => ({ $skip: String(o.skip ?? 0), $top: String(o.take ?? 50) }),
mapResponse: (body) => ({ rows: body.value, totalCount: body['@odata.count'] }),
byKeyUrl: (key) => `/odata/Orders(${key})`,
});
headers is re-read per request, so a token refreshed mid-session reaches the
next call. byKeyUrl is optional — without it the grid does not offer byKey
at all rather than guessing a REST convention that may not be yours.
distinctValues: true offers the header filter's checklist from the same
endpoint (?distinct=<column>&limit=<n>). For the server side,
@kanunilabs/datagrid-server
reads exactly what this sends and answers it from SQL.
Columns
const columns: ReactGridColumnDef<Sale>[] = [
{ field: 'id', headerName: 'ID', dataType: 'number', width: 80, pin: 'left' },
{ field: 'product', headerName: 'Product', width: 220 },
{ field: 'revenue', headerName: 'Revenue', dataType: 'number', width: 140,
valueFormatter: (v) => `$${Number(v).toLocaleString()}` },
{ field: 'status', headerName: 'Status', width: 120, pin: 'right',
renderCell: ({ value }) => <strong>{String(value)}</strong> },
];
dataType (string · number · bigint · date · boolean · lookup) drives sorting,
filtering and alignment. valueFormatter is the cheap path — it returns a
string and is what export and clipboard copy use. renderCell is the expensive
path: arbitrary React per cell.
Pinned columns (pin: 'left' | 'right') are sticky cells inside the single
scroll container. Because there is no second table, the header and body cannot
fall out of alignment.
Other per-column switches: sortable, filterable, groupable, visible,
minWidth/maxWidth, align, and calculateSortValue to sort by a derived key.
hideInChooser: true keeps a column out of the column chooser, the header menu's
Field chooser and the side bar's Columns panel, for a column that exists for the
grid and not for the user; search, filters and export still read it.
Column widths
A column is width pixels wide (150 when not set), and the user can drag its
edge. For a grid that should always fill its container, give some columns a
flex instead:
const columns: ReactGridColumnDef<Order>[] = [
{ field: 'id', headerName: 'ID', width: 80 },
{ field: 'customer', headerName: 'Customer', flex: 1, minWidth: 160 },
{ field: 'notes', headerName: 'Notes', flex: 2 },
];
The columns without flex keep their width; the rest of the grid's width is
shared by the flex columns in proportion — here Notes gets twice what
Customer gets. It is shared again whenever the grid is resized or a column is
shown, hidden or resized. minWidth and maxWidth still hold, and when every
flex column is at its minWidth the grid scrolls sideways.
When the user drags a flex column's edge, or best-fits that one column, it keeps the width they gave it and stops flexing; a saved layout remembers that, and resetting the layout brings the flex back. "Best fit (all columns)" sizes the fixed columns and leaves the flex ones flexing.
To size every column at once, autoSizeStrategy has two modes. 'fitGrid'
scales the widths you set so they fill the grid, again on every resize.
'fitCells' measures the rendered cells once and sizes each column to its
content. A flex column is never changed by either.
Both renderers take the same column definitions.
Large integers
A JavaScript number is exact only up to 2^53 (9,007,199,254,740,991). Past
that it rounds: 9007199254740993 becomes 9007199254740992. A 64-bit id from a
database is often that large, so a column of them needs dataType: 'bigint':
{ field: 'trackingId', headerName: 'Tracking ID', dataType: 'bigint' }
The values can be bigints or the digits as strings — the form a JSON API
sends them in, since JSON has no bigint. The column sorts by exact value,
filters exactly in the filter row, the header popup and the filter builder,
and right-aligns. Filter values are stored as digits, so a saved view stays
valid JSON. Excel export writes the digits as text, since an Excel number would
round them too.
Footer sum, average, minimum and maximum stay blank on a bigint column:
they are JavaScript numbers and would show a rounded result. Count and
distinct count work. Editing keeps a bigint cell a bigint, and a cell
that held digits as text keeps them as text.
A string column of long numeric ids filters exactly too: two ids that differ only past the 16th digit never match each other's filter.
Renaming columns in the grid
Enterprise. Let the people using the grid call a column what they call it:
<EnterpriseDataGrid columnRenaming />
"Rename column" in the header's right-click menu — or F2 on a
focused header — turns the header into a name box. Enter or clicking
away keeps the name, Escape keeps the old one, and an empty box goes
back to the name in your column definition. The grid's own columns (selection,
row numbers, commands) and the group column are never offered; pass a function
to choose the rest, columnRenaming={(columnId) => columnId !== 'id'}.
The new name is what the grid shows everywhere a column is named — the header,
the column chooser, the group panel, menus, filter descriptions and the headers
of an export. It is part of the column state, so a saved view
or a remembered layout brings it back and resetting the columns drops it.
Formulas keep using the names in your definitions, so renaming "Unit price"
does not break [Unit price] * [qty].
Each rename fires columnRenamed with the old and new name; from code,
setColumnHeaderName(columnId, name) does the same (null goes back).
Multi-level headers (bands)
band puts a caption row above a group of columns. One string is one level; an
array is several:
{ field: 'units', headerName: 'Units', band: ['Sales', 'Volume'] },
{ field: 'unitPrice', headerName: 'Unit price', band: ['Sales', 'Money'] },
{ field: 'revenue', headerName: 'Revenue', band: ['Sales', 'Money'] },
A band is a path on the column, not a nested column tree. The list stays flat, so widths, order, pinning, visibility, saved views, the column chooser and virtualization all keep working exactly as they do without bands.
Adjacent columns whose paths agree merge into one band cell. Two consequences worth knowing:
- A band splits when a column that is not in it sits between its members — a cell spanning a column that does not belong to it would be a lie. Reorder the columns together and the cells merge.
- Same-named bands under different parents stay separate:
Q1 › TotalandQ2 › Totalare two Totals, never one spanning both quarters.
Bands never cross the seam into a pinned block, and a column with no band at a given level simply has its own header reach up through it.
Wrapping header text
Free. A long caption on a narrow column ends in an ellipsis. wrapHeaderText
lets it break onto more lines instead, and the grid's autoHeaderHeight lets the
header row grow to fit the tallest one:
<DataGrid
autoHeaderHeight
columns={[
{ field: 'product', headerName: 'Product', width: 200 },
{ field: 'netRevenue', headerName: 'Net revenue after returns and discounts',
dataType: 'number', width: 110, wrapHeaderText: true },
]}
…
/>
createGrid takes the same two options. Without autoHeaderHeight the header
keeps the theme's height and a wrapped caption is cut at its bottom edge.
With it, the bands above the header stay where they are, and the filter row,
pinned rows, totals shown at the top and sticky group headers move down with
it. The height is measured from the columns on screen, so scrolling sideways
onto a longer caption can make the header grow then.
Columns from the data
With an array data source and no columns, one column per field is derived
from the rows:
<DataGrid dataSource={rows} rowKey="id" />
Field names are humanised (unitPrice → "Unit price", SKU stays "SKU",
customerId → "Customer ID") and data types are inferred by sampling — so
sorting a number column is numeric, not lexical. The sample is capped (50 rows
by default) rather than scanning the whole set, a column whose first values are
all null keeps looking, and a column that is null all the way down stays
untyped rather than being guessed at.
Tune it with autoColumns:
<DataGrid
dataSource={rows}
rowKey="id"
autoColumns={{
sampleSize: 200,
exclude: ['internalRef', 'rawPayload'],
defaults: { width: 140 },
}}
/>
A declared columns list always wins — this only fills in what you did not
write. A remote DataSource must declare its columns: there is nothing to
sample before the first fetch, and inventing them after it would reshape the
grid under the user.
Row drag & drop
rowDrag puts a grip at the start of each row on hover. Drag it to reorder:
<DataGrid dataSource={rows} rowKey="id" rowDrag={{ enabled: true }} />
Who owns the order is the decision to make. With no onReorder, the grid
moves its own array — fine when you hand it the data once. With a handler, you
own it and the grid changes nothing:
rowDrag={{
enabled: true,
onReorder: ({ dragKey, targetKey, position }) =>
api.move(dragKey, targetKey, position), // and re-render from your state
}}
If you keep the rows in component state, use the handler. Otherwise the next time you set that state you hand the grid a fresh array in the original order and every reorder silently disappears.
Reordering the grid's own array only works on an unsorted view: with a sort
active the sort decides the order, so the drop would be invisible. Rather than
move a row that visibly snaps back, the grid refuses and says why under
debugMode. To reorder a sorted grid, sort by an order field and rewrite that
field from onReorder — then the move is what the sort sees.
Dropping in the empty space below the last row sends it to the end.
Between two grids — give both the same group:
<DataGrid gridId="backlog" rowDrag={{ enabled: true, group: 'tasks',
onAdd: ({ row }) => setBacklog((l) => [...l, row]) }} />
<DataGrid gridId="sprint" rowDrag={{ enabled: true, group: 'tasks',
onAdd: ({ row, rowKey }) => { setSprint((l) => [...l, row]); removeFromBacklog(rowKey); } }} />
onAdd fires on the grid that receives the row, with the row itself — no
round trip needed. Removing it from the source is the app's call, because only
the app knows whether a cross-grid drag is a move, a copy, or an assignment.
Two grids without a shared group ignore each other, which is what you want
when a page has several unrelated grids.
Merged cells
Enterprise. spanRows draws one box over consecutive rows that hold the same value:
const columns = [
{ field: 'region', spanRows: true },
{ field: 'product' },
];
It is computed over the current view, which is the point — sorting a column
into A A A B B is what makes the merge meaningful, and the same rows unsorted
merge nothing. Sort, filter or edit and the blocks recompute.
Three rules that a plain "merge equal values" gets wrong:
- Blanks never merge. Twelve empty cells are twelve rows that happen to have nothing, not one twelve-row empty cell.
- A group banner interrupts a run. Rows either side of one are not adjacent to a reader, and the block would be drawn straight through it.
- A run of one is an ordinary cell, not a one-row block.
Pass a function instead of true for values that need their own equality — a
column of objects, or a case-insensitive code:
{ field: 'code', spanRows: (a, b) => String(a.value).toLowerCase() === String(b.value).toLowerCase() }
Only the drawing is merged. Selection, editing, the clipboard and export all still see the rows your data has — a block over five rows is five cells, which is what makes it safe to turn on over data you edit.
A block longer than the screen is clipped to what is rendered, so the value stays visible while you scroll through it rather than sitting at a top you scrolled past. Sorting a million rows by a five-value column is a legitimate thing to do; drawn at full height that block would be a 38-million-pixel element.
Spanning columns
colSpan draws a cell across the columns after it. It is asked per row, so a
section heading can run across the grid while the rows under it stay cell by
cell:
{
field: 'title',
colSpan: ({ row }) => (row.kind === 'section' ? 4 : 1),
}
The answer counts the cell itself; anything below 2 is an ordinary cell. The
cell is drawn at the width of the columns it covers, and the covered cells are
not drawn — on screen, and for a screen reader, which hears one cell with
aria-colspan. The arrow keys step over the whole span.
A span stays inside its block: it never runs from a pinned column into the
scrolling ones, and it stops at a sticky column. A longer answer is cut
there. A span that starts left of the columns on screen is still drawn when
you scroll sideways.
As with merged cells, only the drawing spans. Sorting, filtering, copying and export see every column of the row, the covered ones included.
Tooltips
With nothing configured, a cell whose text does not fit shows it in full in a tooltip. A column can say something else:
| Column option | Shows |
|---|---|
tooltip: 'text' or tooltip: (ctx) => text | Your text; null from the function shows none |
tooltipField: 'statusDetail' | Another field of the row |
renderTooltip: (ctx) => … | Rich content — an image, a small table, a link. A React element in React, a DOM node (or text) in plain JavaScript |
headerTooltip: 'text' | The header's tooltip |
The grid-wide tooltip option decides how they open:
<DataGrid tooltip={{ trigger: 'both', interactive: true, delay: 300 }} />
trigger—'hover'(default),'focus'or'both'. With focus, the tooltip follows the focused cell: arrowing onto a cell opens it, and so does tapping a cell on a touch screen, where there is no hover. It is tied to its cell witharia-describedby, so a screen reader reads it with the cell, and Escape closes it. A cell focused from code while the user is elsewhere on the page opens nothing.interactive— the pointer may move onto the tooltip and rest there, to select its text or click a link in it; it closes when the pointer leaves it. Off by default, so a tooltip never stands between the pointer and the next cell.delay(ms, default 400),showOnTruncation(default true) andenabled.
A cell note outranks all of these: a person wrote it about that cell.
Cell notes
Enterprise. Prose a person attached to a cell — Excel's comments. Not a tooltip: a tooltip describes what the cell already says, a note is something someone added that is not in the data, so it carries a corner marker you can see without hovering.
const [notes, setNotes] = useState(new Map<string, string>());
const key = (rowKey, columnId) => `${rowKey}:${columnId}`;
<DataGrid
dataSource={rows}
rowKey="id"
notes={{
get: ({ rowKey, columnId }) => notes.get(key(rowKey, columnId)) ?? null,
onChange: ({ rowKey, columnId, text }) =>
setNotes((prev) => {
const next = new Map(prev);
if (text === null) next.delete(key(rowKey, columnId));
else next.set(key(rowKey, columnId), text);
return next;
}),
}}
/>
Storage is yours. The grid renders notes, reveals them on hover and collects edits; it does not decide where they live, because a note that survives a reload has to go somewhere only your app knows about.
get runs for every rendered cell, so make it a lookup — a Map keyed by
rowKey:columnId is the shape that fits. Anything that scans turns a viewport
into quadratic work.
Giving onChange is what makes notes editable: the grid then adds Add /
Edit / Delete to the row context menu for the cell under the pointer.
Ctrl+Enter saves, Escape cancels, and saving an empty note deletes it — a marker
on a cell whose note says nothing lies about there being something to read. Pass
menu: false to place those actions yourself.
A note outranks the column's tooltip, its tooltipField and the clipped
text. Those describe the column or repeat what is on screen; neither should hide
something a person wrote.
Aligned grids
Two grids that have to read as one table — a scrolling body with a fixed totals strip under it, a master and a detail over the same columns. Give them the same name:
<DataGrid gridId="body" dataSource={rows} columns={cols} alignedGrids="sales" columnResize />
<DataGrid gridId="totals" dataSource={totals} columns={cols} alignedGrids="sales" />
Resize, move, hide or pin a column in one and the others follow; scroll one sideways and the others keep pace.
Sort, filter, selection and vertical scroll deliberately do not travel. Aligned grids share a shape, not a result — a totals strip that re-sorted itself because the grid above it did would be answering a different question. Columns a peer does not have are ignored, so a three-column strip aligns under a twelve-column grid.
Row numbers
rowNumbers adds a leading column numbering the rows:
<DataGrid dataSource={rows} rowKey="id" rowNumbers />
The number is the row's position in what is shown. It renumbers after a sort or a filter, because that is what people mean by "the third row" — they mean the third one on screen. If you need a number that follows a record around, that is a column of your data, not this.
Three things follow from that:
- Pagination continues the count. Page 2 of 50 starts at 51. A second page starting at 1 again tells you nothing about where you are.
- Group headers get no number. A banner is not a record, and numbering it would push every row below it one past the count in the footer.
- Pinned rows get no number. They sit outside the result rather than at a position in it — otherwise a pinned row and the first data row would both claim to be row 1.
Sorting
Click a header to cycle ascending → descending → unsorted. With
sorting={{ multi: true }}, Shift+click adds a second key and the
header shows its position.
Sorting is Intl.Collator-based for text, chronological for dates, and blanks
always sort last regardless of direction.
Sorting by magnitude
A variance or profit-and-loss column usually wants its biggest movements
together, whatever their sign. absoluteSort orders a number column by its
absolute value — −50 and +50 sit side by side, and descending puts the largest
deviation first:
const columns = [
{ field: 'account', headerName: 'Account' },
{ field: 'variance', headerName: 'Variance', dataType: 'number', absoluteSort: true },
];
The cells still show their sign; only the order changes. Blanks stay last, and
two values of the same size keep their data order. It applies to
calculateSortValue when the column has one, and gives the same order whether
the grid sorts on the main thread or in its Web Worker. It is ignored on a
column with a comparator (the comparator decides) and on a column you group
by, where −50 and +50 are two different groups. A server-side DataSource
sorts the way your server does.
The click cycle
By default a header click steps ascending → descending → unsorted. Change it for
every column with sorting.cycle, or for one column with sortCycle; the
column wins:
<DataGrid
sorting={{ cycle: ['asc', 'desc'] }} // never back to unsorted once sorted
columns={[
{ field: 'name', headerName: 'Name' },
// A figures column whose first click should show the largest.
{ field: 'revenue', headerName: 'Revenue', dataType: 'number', sortCycle: ['desc', 'asc', null] },
]}
/>
null is "unsorted". Each click moves to the next entry, wrapping round; a
column whose state is not in its cycle starts at the first entry. The cycle only
governs the header click — setSort() can still set any direction.
Reordering after the sort
sorting.postSort gets the final say on the order. It receives the filtered rows
in sorted order and may rearrange them in place or return them in a new order —
the classic case is a "Total" row that stays at the bottom whichever way a column
is sorted:
const totalLast = (rows) => [
...rows.filter((row) => !row.isTotal),
...rows.filter((row) => row.isTotal),
];
<DataGrid sorting={{ postSort: totalLast }} />;
- It must return the same rows. An answer that adds or drops a row is ignored — the grid keeps its own order and says so once in the console.
- It runs on every pass, also when nothing is sorted, so a pinned-last row stays
last in every view. The second argument says which sort is active:
postSort(rows, { sort, group }). - With grouping on, it is called once per group with that group's rows, and
groupnames the group. A row can never be moved out of its group. - Large grids sort in a Web Worker, and a function cannot be sent there. The hook therefore runs on the main thread after the worker's answer: the worker still does the sorting, and reordering a sorted list is cheap. Keep it fast and free of side effects.
- In React the grid always calls the function from the latest render, without
re-sorting just because a new function arrived. When the rule itself changes
(a "keep totals last" toggle), call
controller.refresh(). In JavaScript,grid.controller.setPostSort(fn)replaces it and re-sorts. - Client data only: a server-side
DataSourcereturns rows in its server's order, and the grid warns if both are configured.
Row animation
<DataGrid animateRows />
When a sort, a filter, a grouping or a data change puts the rows in a new order, each row on screen glides from its old place to its new one instead of jumping, and rows that come into view fade in. It is how a reader follows a row they were looking at through the reorder.
Off by default, and off whenever the operating system asks for reduced motion. Only the rows on screen move — the rest of a million-row result is not animated, so the cost does not grow with the data. Scrolling never animates.
It also matters for Core Web Vitals on a page with live data. When rows
arrive or reorder with no click or key press from the visitor — a feed, a
timer, a server push — the browser counts every row pushed down as layout shift
(CLS). The React grid moves its row elements, so each inserted row costs about
0.01 on a desktop screen and 0.017 on a phone (measured in Chrome). With
animateRows the rows travel by transform, which the browser does not count:
the same page measured 0. A visitor who asks for reduced motion gets no
animation, and the shifts count again.
Filtering
Three independent mechanisms, combined with AND:
Filter row (filterRow) — one input per column. Numeric and date columns
accept operator prefixes:
>=100 <50 <>0 2024-01-01
A date column's box also takes a relative period by name, in the grid's
language or in English: this month, last week, the last 30 days (bu ay,
geçen hafta and son 30 gün in a Turkish grid). The box suggests the names
as you type. The filter keeps its meaning: "this month" set today still means
this month next month. It is stored as a period condition (see the
filter builder). In the React grid, a period
restored from a saved view shows its name in the box again.
Header filter popup (headerFilter) — an Excel-style checklist of the
column's distinct values, with a search box. The list is complete — every
distinct value, even when every row is unique: it's windowed (~20 DOM nodes at
any length), and on large columns it's prepared in background slices behind a
loader so the page never freezes. Fully keyboard-driven: arrows to move,
Space to toggle, Backspace to jump back into the search
box, Enter to apply. Open it from the keyboard with
Alt+↓ on a focused header. Tab goes round inside
the popup, and Esc returns the focus to the header (to the funnel
button, or to the header cell while the button is hidden).
The checklist tells values apart that look alike. A missing value (null) is the
(Blanks) row; an empty string is (empty text); a run of spaces is
(1 space), (2 spaces) and so on. When the column has blanks, a
(Non-blanks) row selects everything else, and is applied as one isnotnull
condition. The words come from the dictionary (filterBlank, filterNonBlank,
filterEmptyText, filterSpace, filterSpaces). The rows read like the cells:
a column with a valueFormatter, a lookup or a dateFormat lists what it
shows. On a text column = and in compare as text, so "", " ", 0 and
012 are four different values.
Where a filter builder can be opened, the popup's first entry is (Custom…); see the filter builder.
Programmatic filters — a serializable AST:
controller.setFilter({
logic: 'and',
nodes: [
{ columnId: 'region', operator: '=', value: 'Marmara' },
{ columnId: 'revenue', operator: 'between', value: [1000, 5000] },
],
});
Operators: = <> > >= < <= contains notcontains startswith
endswith isnull isnotnull in notin between, plus any a column registers
itself (see Your own operators). notin is the exact
complement of in — a value not in the list, blank cells included; it is what
"everything except these" in a server-side header checklist becomes.
Free-text search scans every visible column:
controller.setSearchText('istanbul');
It matches what the cell shows as well as the stored value: a lookup
column's label, a valueFormatter's output and a date column's dateFormat
rendering. A date stored as 2026-09-22 and shown as 22.09.2026 is found by
22.09; an object column formatted with JSON.stringify is found by the text
inside it. The stored value still matches too.
Matching ignores case, and treats İ, I, ı and i as one letter:
istanbul finds İSTANBUL, and yilmaz finds Yılmaz. Plain lower-casing
cannot do this — "İ".toLowerCase() is an i followed by a combining dot — so
without it a Turkish search found nothing. The same rule applies to the
contains / startswith / endswith filters and to the search box in the
header filter popup; = and in stay exact.
Accents still count by default: siparis does not find Sipariş. To make
ç ş ğ ö ü â î û match their plain letters too, set searchFold:
<DataGrid searchFold="tr-loose" … />
It takes the lookup editors' matchFold modes — 'case' (the default above),
'case-accent' (strict Turkish casing, accents dropped) and 'tr-loose' (accents
dropped, and İ I ı i one letter) — and applies to quick search, its highlight
and find. controller.setSearchFold(mode) changes it on a live grid. A server
grid receives the search text as typed.
Formatted text is searched at a cost. Below the worker threshold the formatter
runs per row per keystroke; above it, each formatted column gets a text lane
the first time a search runs — measured at about a second per column at a
million rows (an Intl currency formatter), paid once and kept up to date
through edits.
Your own operators
When the built-in operators cannot say it ("is a weekend", "within 5 km",
"is a multiple of"), a column brings its own with filterOperators:
const columns = [
{
field: 'shipped',
dataType: 'date',
filterOperators: [
{
id: 'weekend',
label: 'is a weekend',
operandType: 'none', // no value to type
test: (value) => [0, 6].includes(new Date(String(value)).getDay()),
},
],
},
{
field: 'qty',
dataType: 'number',
filterOperators: [
{
id: 'multipleOf',
label: 'is a multiple of',
operandType: 'number', // the typed text becomes a number
test: (value, operand, row) => Number(value) % Number(operand) === 0,
},
],
},
];
The condition stays plain data, { columnId: 'qty', operator: 'multipleOf', value: 12 }, so setFilter, setColumnFilter, getViewState and saved views
take it like any other. The operator shows up wherever operators are offered:
- Filter row: the column's cell gets a small operator menu before the box.
Default keeps the usual typed rules (
>100); picking one of the column's operators turns the text into its operand. An operator withoperandType: 'none'filters as soon as it is picked. - Filter builder (Enterprise): listed next to the built-ins for that column.
- Filter panel and
describeFilter: the condition reads with the operator'slabel. - AI state schema (Enterprise): offered for that column, and accepted back
by
applyAiState.
Four things to know:
- It runs on the main thread.
testis a function, and a function cannot be sent to the Web Worker. A query that uses a custom operator is filtered and sorted on the main thread whatever the row count, the same as a customcomparatororsetExternalFilter. Keeptestfast: it runs once per row on every pass. - A server-side source gets only the id and the operand. Your server
implements the operator;
testis never called for a remote grid. - An operator nobody registers matches no row. A saved view restored into a
build that dropped the operator keeps the condition but shows no rows for it,
instead of quietly showing everything. With
debugModethe console names the column and the operator. Atestthat throws counts as "does not pass". - Built-in ids are reserved. An operator whose
idis=,containsor another built-in is ignored, with a console warning.
Your own filter UI
renderFilter replaces a column's filter UI with yours: a range slider, a
date picker, a tag list. It draws in the filter row's cell (surface: 'row')
when filterRow is on, and inside the header popup (surface: 'popup') when
headerFilter is on. setValue takes any filter for the column, including one
that uses a custom operator, or null to clear it. It goes through the same
setColumnFilter call as the built-in box and checklist, so the funnel, the
filter panel and saved views all see it.
{
field: 'qty',
dataType: 'number',
renderFilter: ({ value, setValue, surface, close }) => (
<QtyRange
compact={surface === 'row'}
value={value}
onChange={(min, max) => {
setValue(min == null ? null : { columnId: 'qty', operator: 'between', value: [min, max] });
if (surface === 'popup') close();
}}
/>
),
}
value is the filter that surface holds, read again after every filter change,
so your control follows a cleared filter or a restored view. In the JavaScript
grid, renderFilter(host, api) builds the control into host and may return a
teardown. The control is built once, so it reads api.getValue() and
subscribes with api.onValueChange(listener). The filter row rebuilds its
cells when the columns change or scroll sideways, so seed the control from
api.getValue() each time it is built.
Reading a filter back
describeFilter turns the AST into a sentence, resolving column ids to their
header names and lookup codes to their labels — so a user who arrives at a grid
showing 12 of 100.000 rows can see why:
describeFilter(controller.getFilter(), controller.getColumnModel());
// "Revenue > 50000 and (Region is Marmara or Region is Aegean)"
EnterpriseDataGrid already shows this above the grid when filterBuilder is
on. Pass labels to translate the operator words, and maxListValues to
change when a long in list collapses to "5 values".
Find without filtering
Enterprise. Quick search narrows the rows; find leaves every row where it is and steps through the cells that contain the text, the way Ctrl+F does in a spreadsheet:
<EnterpriseDataGrid find />
Ctrl+F (⌘F) inside the grid opens a find bar above it. Every matching cell is tinted, the current one stronger, and the bar counts them ("3 of 17"). Enter and Shift+Enter — or F3 and Shift+F3 — move to the next and previous match and scroll to it; Escape closes the bar and leaves keyboard focus on the current match. The browser's own find cannot do this on a grid: it only sees the rows that are drawn.
It matches what a cell shows — a lookup's label, a formatted number, a formatted date — with the same case folding as quick search, so "istanbul" finds "İSTANBUL". It searches the rows the grid displays: the current page, and not the rows inside a collapsed group. A new sort, filter or data change updates the matches, and the current one stays current while it still matches.
From code, without the bar: setFindText(text), findNext(),
findPrevious(), clearFind(), getFindState() and the findChanged event.
Grouping and summaries
<DataGrid grouping={{ groupBy: 'region', panel: true }}
summaries={[{ columnId: 'revenue', type: 'sum' }]} />
Single-level grouping produces collapsible group headers with member counts.
The group panel lets users drop a column to group by it (with a <select>
fallback so it works from the keyboard).
Footer summaries support sum avg min max count countDistinct, plus
type: 'custom' with a calculate function that receives the visible cells in
view order. Blanks are skipped rather than counted as zero, so [10, null, 20]
averages to 15 — spreadsheet semantics.
Above ~100k rows the summary pass streams in slices so the rows never wait for
the footer: contentReady fires first, the totals land moments later with a
summariesChanged event. Sorting re-runs a custom summary by default because
its cells arrive in view order; if your calculate doesn't care about order
(sums, ratios, averages), declare dependsOnOrder: false and re-sorting skips
it entirely.
Multi-level grouping and per-group aggregates are Enterprise features — pass a
groupBy array and groupSummaries: true to EnterpriseDataGrid. The
Community grid clamps groupBy to its first level and ignores groupSummaries
rather than half-honoring them.
Cell context menu
Right-click a cell (or press Shift+F10) and the grid
offers its own clipboard and export entries, below whatever rowMenu supplies:
| Entry | Tier | Notes |
|---|---|---|
| Copy | Community | The selected cells, or the selected rows when there is no range. Same code path as Ctrl+C. |
| Copy with headers | Community | One header line above the values. |
| Copy with group headers | Community | Band captions above the header line. Hidden on a grid with no bands, where it would be identical to the entry above. |
| Export ▸ | Community | CSV, Excel, Excel (selected rows), PDF — the same four the toolbar offers. "Selected rows" is disabled with an empty selection. |
| Cut · Paste | Enterprise | Write through the editing engine — one undo step, and validation applies, so a required field refuses to be emptied. Shown only on a cell the permissions allow writing. |
| Chart selected cells ▸ | Enterprise | Opens the chart panel over the selected cells — their columns, and their rows when the range spans several — in the type you pick. |
// Every entry is on by default; this REMOVES rather than opts in.
<DataGrid cellMenu={{ copyWithGroupHeaders: false, export: ['csv', 'excel'] }} />
<DataGrid cellMenu={false} /> // no built-ins; `rowMenu` still shown
Excel and PDF need their optional peers. exceljs and jspdf +
jspdf-autotable are optional peerDependencies, so on a project that never
installed them those two entries throw when pressed. The grid does not hide
them for that: it shows the writer's message — which names the package and the
install command — in an alert at the menu's corner, and logs it. Narrow the
list with export: ['csv'] if you know the peers will never be there.
"Chart selected cells" charts the range's rows. A range over several rows
charts exactly those rows (source: 'range'), and the grid paints the cells the
chart reads; a single row, or a column picked from the header menu, charts the
current view. See
Charting a cell range.
Chrome columns never reach the clipboard. The command column and the row-number column are real columns in the model (that is what makes width, order and pinning work for them), but they hold buttons, not data — copying a row emits the data columns only.
Selection and keyboard
<DataGrid selection={{ mode: 'multiple', checkboxColumn: true }} />
Ctrl/Cmd+click toggles a row and Shift+click
extends a range. A plain click depends on rowClick:
rowClick | A plain click… | Default when |
|---|---|---|
'replace' | makes that row the whole selection | no checkbox column |
'toggle' | adds or removes that one row | checkboxColumn: true |
The checkbox column defaults to toggling because it exists to build a multi-selection — a click a few pixels outside a box should not wipe three ticked rows. A screen whose actions want exactly one row (an "Edit" button that shows only for a single selection) sets it back:
<DataGrid selection={{ mode: 'multiple', checkboxColumn: true, rowClick: 'replace' }} />
The header checkbox follows one rule: if anything is selected, a click clears the selection; if nothing is, it selects every row the current filter matches. So from the mixed (partially selected) state the first click clears and the second selects all — the opposite of what some users expect from a mixed box, so say so in your UI if it matters.
selection.mode can change at runtime; switching to 'none' clears the
selection. Selection is keyed by row identity, so it survives sorting,
filtering and data updates.
Rows that cannot be selected
isRowSelectable decides which rows may be selected — a closed order, a locked
record, a row the user has no rights to:
<DataGrid
selection={{
mode: 'multiple',
checkboxColumn: true,
isRowSelectable: (order) => order.status !== 'closed',
}}
/>
Every way of selecting respects it. The row's checkbox is drawn disabled; a
click, Space and Shift+click range pass over the row;
select-all and a group's checkbox skip it; selectRow, toggleRow and
setSelectedKeys ignore it. The selected count and the header checkbox count
the selectable rows only, so after select-all the header box reads "all", and
it is disabled when nothing in the result can be selected.
controller.isRowSelectable(key) and getSelectableCount() give your own UI
the same answers.
The rule is asked again whenever the data changes — setData, a transaction, a
saved edit — and a selected row it now refuses is deselected. When the rule
depends on something else (the user's role changed), pass a new function in
React, or call controller.setRowSelectable(rule) in JavaScript; the grid
re-asks every row and repaints. Answers are remembered per row until the data
changes, so keep the function cheap and free of side effects, and give React a
stable one (useCallback) so it is not re-asked on every render.
With selection.deferred, "everything matching" excludes the refused rows, and
getSelectionDescriptor() lists them among the exclusions — a server applying
the descriptor will not touch rows the user could not tick. On a server-side
DataSource only loaded rows can be asked, so the server should apply the same
rule.
The full keyboard model:
| Key | Action |
|---|---|
| ↑ ↓ ← → | Move focus |
| Page↑ Page↓ | Move a page |
| Home / End | Row start / end |
| Ctrl+Home / End | Grid start / end |
| Space | Toggle selection (or expand a group) |
| → / ← on a group or tree node | Open / close it; ← on a closed tree row goes to its parent. On a tree row only in the first column, where the toggle is |
| Shift+↑/↓ | Extend selection (with Enterprise range selection on: grow the cell range, ←/→ too) |
| Ctrl+A | Select all |
| Ctrl+C | Copy as TSV |
| Esc | Clear selection |
| Alt+↓ | Open the header filter (on a header) |
Accessibility
The accessibility statement covers both grids: keyboard, screen readers, contrast, how it is tested and the known gaps.
role="grid" with aria-rowindex / aria-colindex / aria-rowcount,
aria-selected on rows, and a polite live region announcing row counts, sort
changes and selection size — in the grid's locale, from the same dictionary
as the rest of its text (announceRows, announceSortedBy, announceSelected,
announceAscending, announceDescending; override them through messages).
Focus inside the grid is virtual (aria-activedescendant) because moving
real DOM focus would fight row virtualization. The header uses a roving
tabindex, so the whole header is one tab stop rather than one per column.
Give each grid a name with ariaLabel — it is what a screen reader says when
focus enters the grid. Without it the grid is named by its gridId, which is
an identifier rather than words:
<DataGrid gridId="orders" ariaLabel="Open orders" /* ... */ />
aria-selected is written only where rows can be selected: a grid without
selection, and a pinned row, say nothing about it rather than "not selected"
on every row.
From the keyboard, in both the React and the plain JavaScript grid:
| Where | Key | Does |
|---|---|---|
| Header | ← → Home End | Move between column headers |
| Header | Enter, Space (Shift adds a level) | Sort by the column |
| Header | Alt+↓ | Open the column's filter |
| Header, cell | Shift+F10, the Menu key | Open the column's or the cell's menu |
| Menu | ↑ ↓ Home End, → ← | Move through the items, into and out of a submenu |
| Filter, menu | Escape | Close it; focus returns to where it was opened |
Export and import
const { blob, fileName } = await controller.exportToCsv();
downloadBlob(blob, fileName);
CSV follows RFC 4180 and is written with a UTF-8 BOM so Excel opens it with the
right encoding. Excel export (exportToExcel) needs the optional exceljs
peer and writes numbers and dates as real numbers and dates so they stay
computable.
The CSV delimiter follows the grid's locale. Excel splits a
double-clicked CSV on the list separator of the machine's region, and where
the comma is the decimal mark that separator is ; — a comma-separated file
opens there as a single column. So the default is ; for tr, de, fr,
es, it, pt, ru and ar, and , for en, ja, ko and zh-CN (each
taken from Windows' own regional data). Pass delimiter to choose.
Defaults for the toolbar's buttons. The export buttons call the export methods without arguments, so options they should use are set once, per format:
<DataGrid
onReady={(controller) => {
controller.setExportDefaults('csv', { delimiter: ';' });
controller.setExportDefaults('pdf', { font: { family: 'Noto Sans', normal: notoTtf } });
}}
/>
Explicit arguments still win over these. The one-argument form,
setExportDefaults({ … }), is the original Excel-only signature and keeps
meaning Excel.
Exports reflect what you see: formatted values, visible columns, current sort/filter/grouping, group subtotals — and the whole result, not just the current page. Both formats are produced from one model, so they cannot drift apart.
Past a million rows, Excel gets more sheets. An Excel sheet holds 1,048,576
rows, header included; one more and Excel will not open the file. Rows past the
limit continue on Data (2), Data (3)… (named after sheetName), each with the
header repeated, its own filter and a frozen top row, so every row arrives in a
file Excel opens. maxRowsPerSheet sets a lower limit; it is never raised. CSV
has no limit of its own and is not split — Excel cuts a CSV off at the same row
when it opens one.
Streaming: no row cap. The export above builds the whole file in memory
before handing it over, which is fine at report sizes and the reason a server
grid caps it (remote.exportMaxRows, 100,000 by default). With stream: true
the rows are read a piece at a time — the view in slices, a server source's
pages — and each piece is written and dropped:
controller.setExportDefaults('excel', { stream: true }); // the toolbar button too
const { blob, fileName } = await controller.exportToExcel({ stream: true });
On a server grid set remote: { exportMaxRows: Infinity } to remove the cap. A
source that can hand over a large result its own way (a database cursor, a
streamed response) implements exportRows, and the grid reads it instead of
paging load:
const source: DataSource<Order> = {
load: (options) => api.orders(options),
async *exportRows({ sort, filter, searchText, columnIds }, signal) {
for await (const page of api.ordersExport({ sort, filter, searchText, columnIds }, signal)) {
yield page; // an array of rows
}
},
};
The streamed Excel file is written by the grid itself, with no library to load:
values stay typed (numbers, dates, TRUE/FALSE), each column keeps its number
format (excelFormat), widths, a frozen header and a filter, and past Excel's
row limit the table continues on Data (2). What needs the whole sheet at once
is left out: the styled export's colours and outline, the totals row,
master-detail tables, images, formulas and extra grids. Measured: 1.2 million
rows in about 7 seconds, a 33 MB file that Excel opens.
Cancel (controller.cancel(), or your own signal) and a failure — the server
dropping mid-way — hand over no file. To skip even the finished file in
memory, give writable a stream to write to, such as a file the user picked:
const handle = await window.showSaveFilePicker({ suggestedName: 'orders.xlsx' });
await controller.exportToExcel({ stream: true, writable: await handle.createWritable() });
It is closed when the export completes and aborted when it does not, so a cancelled export leaves no half-written file behind.
Dates are dates in Excel. In a dataType: 'date' column, a Date, an ISO
string ("2011-11-01", "2011-11-01T10:30:00" — what a JSON API sends) and an
epoch number are written as real Excel dates, so Excel's date filter, sort and
grouping work on them. They land on the same local calendar day and clock time
the grid shows: a bare yyyy-mm-dd is that day, not UTC midnight. Text that is
not an ISO date stays text. In CSV and PDF a date column with a dateFormat
reads exactly as its cells do.
Each column's number format — its excelFormat, or yyyy-mm-dd for a date
column and a thousands separator for a number column — is written into a plain
file too; styled adds alignment, banded rows, the outline and the totals row
on top.
Excel: from a dump to a report
Enterprise, like every Excel export. Four options turn the sheet into something you can hand to someone.
Per-cell rules. customizeCell runs for every cell and returns a style to
merge over whatever the writer chose — or nothing, to leave it alone:
await controller.exportToExcel({
styled: true,
customizeCell: ({ kind, columnId, value }) => {
if (kind !== 'data' || columnId !== 'revenue') return;
if (Number(value) < 0) return { fill: 'FFFEE2E2', font: { color: 'FFB91C1C' } };
},
});
kind is header · data · group · totals · band, so a rule can target
the totals row without touching the data. The hook is on the hot path — one
call per cell — so it is skipped entirely when you do not pass one.
Rows above and below the table, for a title, a date, a note:
headerBlock: [
{ cells: ['Quarterly revenue'], merge: true, style: { font: { bold: true, size: 15 } } },
{ cells: [`Generated ${today}`] },
{ cells: [] }, // a blank spacer row
],
footerBlock: [{ cells: ['Figures are unaudited.'] }],
merge spans the row across the table's width. The freeze line and the
auto-filter follow the real header row, so a title above the table does not
push either onto the wrong row.
A logo, anchored in sheet coordinates:
images: [{ data: base64Png, extension: 'png',
position: { col: 5, row: 0, width: 90, height: 30 } }],
More than one grid. A block with a sheetName gets its own sheet; without
one it is stacked below the previous block on the same sheet:
additionalGrids: [
{ model: summaryModel, title: 'By region', gap: 2 },
{ model: detailModel, sheetName: 'Detail' },
],
The auto-filter stays on the first grid's header — Excel allows one per sheet, and pointing it at a stacked block would filter rows the reader is not looking at.
A fileName that already ends in .xlsx is left alone rather than becoming
report.xlsx.xlsx.
Formulas and links
Calculated columns and cell formulas are written as Excel formulas over the
sheet's own cells — =B2*C2, =SUM(C2:C9) — with the grid's result cached
beside them, so the sheet shows the values at once and keeps calculating when
someone edits it. A formula whose cells are not all in the file (a hidden column,
a filtered-out row) is written as its value, and so is one in a cycle; a range
over a sorted grid is written as the cells it means, and a reference into a
continuation sheet is sheet-qualified. formulas: false writes values only. See
Formulas.
A column's exportLink makes its cells hyperlinks in Excel and PDF:
{ field: 'orderNo', headerName: 'Order', exportLink: (row) => `https://shop.example/orders/${row.id}` }
Only http:, https:, mailto: and tel: links are written; anything else —
a javascript: URL above all — is dropped and the cell stays text. CSV writes
the text.
Printing
Ctrl+P on a virtualized grid prints the twenty rows that happened to be on
screen, inside a box the browser has clipped to one viewport. printLayout
fixes that:
<DataGrid dataSource={rows} rowKey="id" printLayout />
On beforeprint the grid renders every row and stops clipping itself, so
the browser paginates real content; afterprint puts it back. Scroll position,
selection and filters all survive — only the rendering changed. Controls that
mean nothing on paper (toolbar, pager, resize handles, funnels) are hidden, rows
are kept from splitting across a page break, and background colours are asked
for explicitly so the header and striping survive Chrome's default.
It refuses above 5.000 rows. Print layout puts every row in the DOM; at a
hundred thousand that is a frozen tab with a print dialog open, which the user
cannot cancel out of. Past the cap the grid prints what it always did and says
so under debugMode. For a result that size use PDF export — it
streams. Move the line with printLayout={{ maxRows: 20000 }} if your rows are
narrow and you have measured it. onLimit tells you when it happened, so the
user is not left wondering why the printout is short:
<DataGrid
printLayout={{ maxRows: 5000, onLimit: ({ rows, maxRows }) => toast(`Only the visible rows were printed (${rows} > ${maxRows}). Export to PDF for all of them.`) }}
/>
The column headers (band rows, header and filter row) repeat at the top of every printed page, and a row is never split between two pages; the summary row prints once, after the last row. To get the browser's page-by-page header, the grid copies itself into a throw-away <table> for the moment of printing and hides the live grid. Turn that off with printLayout={{ repeatHeader: false }} and the header prints on the first page only. PDF export repeats the header and keeps rows whole too.
Your own layout has to let go too. A grid is usually mounted as a flex child filling a viewport-height shell, and the grid can only unclip itself and its own wrappers. While printing it marks the root element, so one rule releases yours:
@media print {
.kanuni-datagrid-printing .my-app-shell {
height: auto !important;
overflow: visible !important;
flex: none !important;
}
}
printLayout={{ always: true }} stays in that mode permanently, for rendering a
grid into a report page where there is no print dialog to react to.
Enterprise. exportToPdf needs the optional jspdf and jspdf-autotable peers — a grid
that never exports PDF should not pay for them, so they are loaded on first use
and a missing install is reported as an install hint rather than a
module-not-found stack.
const { blob, fileName } = await controller.exportToPdf();
downloadBlob(blob, fileName);
The API is deliberately the same as the Excel report's — customizeCell,
headerBlock / footerBlock, additionalGrids, images — so a report you
have already styled for Excel does not need a second vocabulary:
await controller.exportToPdf({
orientation: 'landscape', // default; 'portrait' also accepted
pageSize: 'a4', // 'a3' · 'letter' · 'legal'
pageNumbers: (page, total) => `Page ${page} of ${total}`,
headerBlock: [
{ text: 'Quarterly revenue', fontSize: 15, fontStyle: 'bold' },
{ text: `Generated ${today}`, fontSize: 9, color: [100, 116, 139] },
],
footerBlock: [{ text: 'Figures are unaudited.', fontStyle: 'italic' }],
customizeCell: ({ kind, columnId, value }) => {
if (kind !== 'data' || columnId !== 'revenue') return;
if (Number(value) < 0) return { fillColor: [254, 226, 226], textColor: [185, 28, 28] };
},
additionalGrids: [{ model: detailModel, title: 'Detail', pageBreak: true }],
});
Colours are RGB triples (0–255) rather than the ARGB strings Excel uses, because that is what a PDF actually stores.
Text outside Western European Latin needs a font. Without one, jsPDF draws
with its built-in Helvetica, which covers Latin-1 plus a few typographic marks
and nothing else: Turkish ş ğ ı İ, Central European, Cyrillic, Greek, Arabic
and CJK letters come out as the wrong characters (Kişi became Ki_i,
İSTANBUL became 0STANBUL). Give the export a TrueType font that covers your
language — it is embedded, subset to the glyphs used:
const normal = await fetch('/fonts/NotoSans-Regular.ttf').then((r) => r.arrayBuffer());
const bold = await fetch('/fonts/NotoSans-Bold.ttf').then((r) => r.arrayBuffer());
await controller.exportToPdf({ font: { family: 'Noto Sans', normal, bold } });
// or once, for the toolbar button too:
controller.setExportDefaults('pdf', { font: { family: 'Noto Sans', normal, bold } });
Only normal is required; a missing bold falls back to it, so headers and
totals stay in the right script (merely not emboldened). The file must be a
.ttf — jsPDF does not read .otf or WOFF, and the export says so if it is
handed one. When a PDF export meets text the built-in font cannot draw and no
font was given, it warns in the console, naming the first such character.
Large tables are laid out in slices. autoTable lays a table out in one
synchronous call, so past ~400 rows the writer feeds it a slice at a time and
yields between them — onProgress ticks, signal can cancel, and the tab
stays alive instead of freezing until the file is done. Measured on the bench
at 4.000 rows × 15 columns:
sliceRows | Total | Longest freeze |
|---|---|---|
0 (one call) | 14,9 s | ~15 s |
| 1000 (default) | 12,8 s | 3,3 s |
| 500 | 13,0 s | 1,9 s |
Slicing costs nothing in total time — but the slices must not get too small:
every call redoes its own setup, and an early attempt that sliced one PAGE at a
time (≈45 rows) took minutes. Set sliceRows lower for shorter freezes,
or 0 to force the single call and the tightest possible document.
PDF is not a format for a million rows. The measurements above scale linearly: that 4.000-row file is already 18 MB, so a million rows is gigabytes and hours whatever the slicing. Use CSV or Excel at that size, or filter first.
Three behaviours worth knowing:
Column headers repeat on every page (repeatHeaders, default on). A table
that spills onto page three with no headings is unreadable on paper, where you
cannot scroll back up to check which column is which.
PDF carries the formatted text, where Excel writes raw numbers and dates. A PDF is a picture of the data, not a spreadsheet you go on computing with, so there is nothing to gain from a raw value that then has to be formatted for drawing anyway.
A footer that would not fit gets its own page. Text drawn past the page edge is simply invisible, so the note would silently vanish exactly when the report is long enough to need one.
If images data is not a real file of the declared format, the export fails
with a message naming which image and why. jsPDF decodes an image to read its
dimensions, so a malformed one cannot be embedded — unlike Excel, which stores
the bytes without looking at them and would produce a quietly broken file.
CSV import sniffs the delimiter (, ; tab |), infers column types, and
reports malformed rows instead of hiding them:
const { columns, rows, malformedRows } = importCsv(text);
Pagination and toolbar
<DataGrid pagination={{ enabled: true, pageSize: 100 }} toolbar />
Pagination and virtualization coexist — the pager slices the view and the window still virtualizes the page. Changing a filter resets to page 1.
Numbered pages
With pageButtons the pager shows page numbers between the previous and next
buttons, so a user can jump straight to a page:
<DataGrid pagination={{ pageSize: 50, pageButtons: true, maxPageButtons: 7 }} />
With more pages than fit, the run is shortened with an ellipsis — 1 2 3 4 5 … 40 at the start, 1 … 19 20 21 … 40 in the middle — and the first page, the
last page and the current one always stay. maxPageButtons caps the slots,
ellipses included (default 7, at least 5). The current page's button carries
aria-current="page", every number is a real button named in the grid's
language ("Page 3", "Sayfa 3"), and keyboard focus stays on the button you
pressed while the pages move round it. The same options work in
createGrid.
The toolbar provides debounced search, a column chooser and export buttons. Your own controls go beside them rather than in a second bar above:
<DataGrid
toolbar
toolbarItemsBefore={<button onClick={refresh}>Refresh</button>}
toolbarItemsAfter={<button onClick={openReport}>Report…</button>}
/>
toolbarItemsBefore puts them at the start, before the search box;
toolbarItemsAfter at the end, after the grid's buttons.
Pick the toolbar's parts
toolbar also takes an object. Each part is on unless you turn it off, so
this is the toolbar with only its search box:
<DataGrid toolbar={{ export: false, columns: false }} />
The Enterprise grids add a Chart button when charting is on; chart: false
leaves it out for an app that opens the chart from a button of its own.
| Part | What it is | Default |
|---|---|---|
search | The quick search box, or its settings (below) | true |
columns | The Columns button | React true; createGrid follows toolbarColumnChooser (off) |
export | The export menu: CSV, plus Excel and PDF where toolbarExcel / toolbarPdf and the edition allow | true |
toolbar={true} and toolbar={false} mean what they always did.
The search box takes its own settings:
<DataGrid
toolbar={{
export: false,
search: {
placeholder: 'Search orders…',
ariaLabel: 'Search orders', // what a screen reader calls the box (default: the dictionary's)
maxLength: 100, // the input's maxLength
debounce: 300, // ms after the last keystroke (default 200)
applyOnBlur: true, // search at once on blur and on Enter (default true)
validate: (text) => // a message refuses the text; null accepts it
/\p{Extended_Pictographic}/u.test(text) ? 'Emoji cannot be searched' : null,
},
}}
/>
A text that validate refuses is shown under the box and never searched,
so the grid keeps the last search that passed. On a server-side grid the
text reaches your load as searchText, as before — trimmed: the spaces typed
around it match nothing and are not sent.
The box shows the grid's search wherever it was set: setSearchText, or a saved
view restored after the toolbar appeared. On a phone it takes the toolbar's
whole first line; on a touch screen it is a 44 px target with 16 px text.
Your own buttons, drawn like the grid's
GridToolbarButton (React) and toolbarButton() (plain JavaScript) make an
icon button with a name, a shortcut hint and, while it cannot be used, the
reason. Put them in the toolbar or in the status bar's items:
import { GridToolbarButton } from '@kanunilabs/datagrid-react';
<DataGrid
toolbar={{ export: false }}
toolbarItemsAfter={
<GridToolbarButton
icon={<ExcelIcon />}
label="Export to Excel"
shortcut="Ctrl+E"
disabledReason={rows.length === 0 ? 'Nothing to export' : undefined}
onClick={exportToExcel}
/>
}
/>
import { createGrid, toolbarButton } from '@kanunilabs/datagrid';
const send = toolbarButton({ icon: '<svg>…</svg>', label: 'Send', shortcut: 'Ctrl+Enter', onClick: sendSelection });
createGrid(host, { toolbar: { export: false }, toolbarItemsAfter: [send] /* … */ });
send.update({ disabledReason: 'Nothing selected' }); // later
An unavailable button stays focusable (aria-disabled, not disabled), so
the keyboard and the mouse can both reach the reason; its clicks are ignored.
Popups inside a modal: portalContainer
The grid draws its popups (header filter, menus, the date and lookup lists,
dialogs, tooltips) outside its own box, on document.body, so the grid's
overflow cannot clip them. Inside a modal such as a Radix Dialog that is the
wrong place: the modal makes the rest of the page ignore the pointer, so a
click in the popup falls through to the layer below and the popup closes.
Draw them inside the modal instead:
const [modal, setModal] = useState<HTMLElement | null>(null);
<Dialog.Content ref={setModal}>
<DataGrid portalContainer={() => modal} /* … */ />
</Dialog.Content>
portalContainer is an element or a function returning one (read each time a
popup opens, so a ref that is not set yet is fine). It works in createGrid
too. Pass the modal's content element, one without overflow: hidden. Popups
stay under the control that opened them even when the modal is centred with a
CSS transform.
Every popup the grid draws carries data-kanuni-portal, so your own click
handling can tell a click in the grid's popup from one outside it:
if ((event.target as Element).closest('[data-kanuni-portal]')) return; // the grid's own popup
A popup closes only through its own buttons, Escape, or a click outside it.
Saved views
const view = controller.getViewState(); // JSON-safe
controller.applyViewState(view);
Captures column widths, order, pinning and visibility, plus sort, filters,
search, grouping, which groups are collapsed and pagination. It also keeps
what the user changed from the menus: the footer's aggregation for each column
(a custom one comes from your configuration and is not saved, since its
reducer is a function), group footers on or off, folded column bands, and under
server-side grouping which groups were open.
Selection, focus and scroll
These describe a moment rather than a layout, so a view leaves them out unless you ask for them:
const view = controller.getViewState({ include: ['selection', 'focus', 'scroll'] });
'ranges' adds the Enterprise cell ranges (columns by id, so a range saved
over a column comes back over it after a restored column order), and
'details' the open detail panels, by row key — a saved view restores with
every panel closed, a tab rebuilt from its own snapshot should not. A restored
focus and scroll wait until the rows are there; on a server source the focus
waits for its row's block, which the restored scroll asks for. A restored selection drops keys
the data no longer has; "everything matching" comes back as it was, exclusions
included. Restoring never clears what a view does not carry — a view without a
selection leaves the current one alone.
Remembering the layout automatically
stateStoring does the same thing without you writing the wiring: it restores
once on mount and saves on every layout change, debounced.
<DataGrid stateStoring={{ enabled: true }} />
It saves after every change the view carries — stateUpdated fires for each,
including a collapsed group, a turned page and a changed footer aggregation.
Session state is kept only when you name it:
<DataGrid stateStoring={{ enabled: true, include: ['selection', 'scroll'] }} />
Off by default, because a reload that brings yesterday's selection back over today's rows selects rows nobody chose today.
The key defaults to kanuni-datagrid-<gridId>, so two grids on a page never
share a layout. type chooses 'localStorage' (default), 'sessionStorage'
or 'custom'; custom hands you customLoad/customSave, either of which
may be async, for a layout kept on your server per user.
<DataGrid
stateStoring={{
enabled: true,
type: 'custom',
customLoad: () => fetch(`/api/grid-layout/${userId}`).then((r) => r.json()),
customSave: (state) =>
fetch(`/api/grid-layout/${userId}`, { method: 'PUT', body: JSON.stringify(state) }),
}}
/>
Three behaviours are deliberate. The layout is restored once, at mount — a
later restore would undo the sort the user just asked for. Writes are
debounced (saveDelay, default 500 ms) because dragging a column edge
fires a change per pixel, and a pending write is still flushed when the grid
unmounts. And a failed restore is never fatal: storage that is full,
disabled by privacy settings, or holding a snapshot from an older build leaves
the grid opening with its default layout instead of refusing to open. Under
React's StrictMode, which runs the restore twice, a running customLoad is
shared rather than called again.
Columns hidden by the screen
A column that should give way on a narrow screen says so with hideBelow, the
grid's width in pixels:
const columns = [
{ field: 'customer' },
{ field: 'email', hideBelow: 768 },
{ field: 'phone', hideBelow: 1024 },
];
It is a layer of its own, not the user's choice: the saved view keeps what the
user chose, the column chooser still shows the column ticked, and it comes back
by itself once the grid is wide enough. A column the user hid stays hidden at
any width. Cards on a phone leave it out too; search, filters and export still
read it. Hiding columns for a phone with setColumnVisible would be saved as
the user's choice and stay hidden on a wide screen.
Row template
renderRow replaces a data row's content — a card, a chart line, a summary
sentence — while the header, virtualization, selection and keyboard all keep
working:
<DataGrid
renderRow={({ row, selected }) => (
<div className={selected ? 'row card selected' : 'row card'}>
<strong>{row.product}</strong> — {row.units} × {row.unitPrice}
</div>
)}
/>
Group headers and detail panels keep their own rendering: a template that had to handle those as well would be a template of the whole grid.
What the template replaces are the cells — so while it is on, in-cell
editing, range selection and the fill handle have nothing to attach to. For
per-cell customization that keeps the column layout, use a column's
renderCell instead.
Density
Three presets set the row height, header height, type scale and cell padding together:
<DataGrid density="compact" /* | "normal" | "comfortable" */ />
| Row height | Header | Font | |
|---|---|---|---|
compact | 24 px | 28 px | 12 px |
normal (default) | 28 px | 32 px | 13 px |
comfortable | 36 px | 40 px | 14 px |
The row height is a virtualization value, not only a CSS variable, so switching
density re-measures the scroll extent — a 100.000-row grid goes from a
2.800.000 px canvas to 2.400.000 px on compact. An explicit rowHeight still
wins: density is a shorthand, not an override.
Cards on narrow screens
On a phone, a ten-column table is a sideways scroll through cells that no
longer line up with their headers. cardView draws each row as a card when
the grid is narrower than a breakpoint (600 px by default). The first field is
the card's title, the rest are "Header value" lines, and the column headers
give way to a Sort by control.
<DataGrid cardView dataSource={orders} columns={columns} />
// Your own breakpoint, and the fields a card shows (the first is the title):
<DataGrid cardView={{ breakpoint: 720, columns: ['customer', 'status', 'total'] }} … />
createGrid(element, { cardView: true, /* … */ });
It is the same grid underneath. Sorting, filtering, quick search, selection,
grouping, virtual scrolling and server data keep
working, and a million rows scroll as cards. A group row stays one line. A
card shows each field's text with its formatter or lookup label. A
column's renderCell is not used on a card. While cards are shown they take
the place of renderRow.
Some things need a cell and are off while cards are shown: in-cell editing,
range selection, the fill handle and column resizing. They come back when the
grid is wide again. onCardViewChange(active) tells you when the grid
switches, for example to offer an edit form instead.
Pinned rows
Rows that stay in view while the data scrolls between them, above the body or below it.
Rows the app pins — a target line, last year's figures — are passed in
pinnedTopRows and pinnedBottomRows. They are not data: never sorted,
filtered, paged, selected or counted, and not exported. They share the
columns, widths and cell rendering of a real row, so the two stay aligned.
<DataGrid
pinnedTopRows={[{ id: -1, product: 'Target', revenue: 60_000 }]}
pinnedBottomRows={[{ id: -2, product: 'Last quarter', revenue: 48_616 }]}
/>
Rows the user pins: with rowPinning, the row menu offers "Pin row to
top" and "Pin row to bottom". The pinned row shows in that band, after the
app's rows, and right-clicking it there moves it to the other band or unpins
it.
<DataGrid rowPinning={{ isRowPinnable: (row) => row.status !== 'Draft' }} />
A pinned row is a copy in the band; the row itself stays where it was. It is still counted, sorted, filtered, paged, selected and exported like any other. The copy shows the row's current values, and it stays in the band while a filter hides the row from the body — keeping it in view is what pinning is for. A row deleted from the data is unpinned with it.
From code: pinRow(key, 'top' | 'bottom' | null), getPinnedRowKeys(),
clearPinnedRows(), and the rowPinningChanged event. The pins are part of a
saved view; a key the data no longer has is dropped when the view is restored.
The API works with rowPinning off too — the option is what the menu offers.
Row context menu
<DataGrid
rowMenu={[
{ id: 'copy', label: 'Copy SKU', shortcut: 'Ctrl+C', onSelect: (ctx) => copy(ctx.row.sku) },
{ separator: true },
{ id: 'more', label: 'More', items: [{ id: 'log', label: 'Log row', onSelect: log }] },
]}
/>
Pass a function instead of an array to build the items from the row that was clicked — returning an empty list suppresses the menu for that row:
rowMenu={(ctx) => (ctx.row.locked ? [] : itemsFor(ctx.row))}
The context carries row, node, rowIndex, the columnId under the pointer
and the selectedKeys at the moment the menu opened. Right-clicking a row that
is not selected selects it first, so an action driven by the selection operates
on what the user pointed at.
The menu is keyboard-operable: Shift+F10 or the ContextMenu key opens it on the focused row, arrow keys move (skipping disabled items), → and ← enter and leave a submenu, Enter activates and Esc closes. It is clamped to the viewport, so opening it on the last row does not push it off-screen.
Theming
Styles are plain CSS driven by custom properties, scoped under
.kanuni-datagrid-root:
.kanuni-datagrid-root {
--dg-primary: #7c3aed;
--dg-row-height: 32px;
--dg-border: #e5e7eb;
}
That restyles the grid body only. For a theme that also reaches the popups and
the Enterprise chrome, give it a name and pass it as theme — see
Theming. Pass dark for the
packaged dark palette.
Charts
The chart MODEL is here in Community: useGridChartData() turns the grid's
current result into categories and aggregated series, ready for any chart
library. The panel and its renderers are Enterprise — see
Charts.
import { useGridChartData } from '@kanunilabs/datagrid-react';
const model = useGridChartData(controller, {
categoryColumnId: 'region',
series: [{ columnId: 'revenue', aggregate: 'sum' }],
});
Missing a feature? Tell us
This grid is shaped by the people using it. If something is missing, awkward or broken, we want to hear about it — send us your feedback.