Features guide
Everything below is available in the free @kanunilabs/pivotgrid-react
and @kanunilabs/pivotgrid packages unless a section is explicitly marked
Enterprise. Each feature is
driven by props or per-field configuration — no imperative setup required.
Most features are configured on the PivotField objects you pass to
initialFields (or the controlled fields prop), or on the layout,
stateStoring, theme and toolbar props of BasePivotGrid.
Aggregation
Every measure (a field in the data area) declares a summaryType:
{ id: 'revenue', dataField: 'revenue', caption: 'Revenue', dataType: 'number',
area: 'data', summaryType: 'sum' }
Supported: sum, count, avg, min, max, distinct (distinct count) and
custom. The built-in summaries run in the Web Worker, off the main thread.
Exact decimal totals
Measures are added as JavaScript numbers (doubles), and decimals drift: four
thousand two-decimal amounts can total 343649.74999999994 instead of 343649.75,
and a one-decimal format then writes 343.649,7 where the decimal total reads
343.649,8. Give the field precision, the decimal places of its source
values (2 for a decimal(18,2) column):
{ id: 'qty', dataField: 'qty', caption: 'Quantity', dataType: 'number',
area: 'data', summaryType: 'sum', precision: 2 }
// every cell, subtotal and grand total: 343649.75, never 343649.74999999994
Each value is rounded once to that many decimals (half away from zero) and the
engine adds whole units — cents here — dividing once at the end. It applies to
sum, avg (the exact sum divided by the count), min and max; count,
distinct and custom are unchanged. The display modes, the top-N "Others"
row, summary expressions, the exports (Excel gets 343649.75; its number format
rounds as the screen does) and the selection statistics read the same exact
numbers. A row-level calculateExpression result is rounded like a source
value; a summary expression's own result is not rounded.
Totals are exact up to Number.MAX_SAFE_INTEGER / 10^precision — about 90
trillion at 2; past that they are added as plain doubles, as without the
setting. An integer from 0 to 10 is accepted; anything else is ignored and
reported through onError. With a serverSource the browser does not add:
the request carries precision on each value field and your server sums.
Without precision nothing changes.
Custom summaries
For bespoke rollups, provide calculateCustomSummary (start → calculate →
finalize), the same three-phase model used by classic pivot engines. It runs
once per cell, subtotals and grand totals included, over that cell's own rows:
{ id: 'priceRange', dataField: 'price', caption: 'Price Range', dataType: 'number',
area: 'data', summaryType: 'custom',
calculateCustomSummary: (o) => {
if (o.summaryProcess === 'start') { o.lo = Infinity; o.hi = -Infinity; }
if (o.summaryProcess === 'calculate') {
o.lo = Math.min(o.lo, o.value);
o.hi = Math.max(o.hi, o.value);
}
if (o.summaryProcess === 'finalize') o.totalValue = o.hi - o.lo;
} }
Rows arrive in source order, and anything you store on the options object stays there between phases. The worker groups the rows; your function runs on the main thread, because a function cannot be sent to a worker.
To reuse one summary across fields, register it and refer to it by name. The function receives the cell's values:
import { PivotEngineRegistry } from '@kanunilabs/pivotgrid-core';
const registry = new PivotEngineRegistry();
registry.registerAggregator('median', (values) => {
const s = [...values].sort((a, b) => a - b);
const m = s.length >> 1;
return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
});
// pass `registry` to the grid, then:
{ id: 'medianPrice', dataField: 'price', caption: 'Median Price', dataType: 'number',
area: 'data', summaryType: 'custom', calculateCustomSummary: 'median' }
A name that is not registered stops the grid with an error that names it, instead of quietly showing a sum.
Summary display modes
Transform an aggregated value after it is computed with summaryDisplayMode:
{ id: 'revenue', dataField: 'revenue', caption: '% of Total', dataType: 'number',
area: 'data', summaryType: 'sum', summaryDisplayMode: 'percentOfTotal' }
| Mode | Shows each cell as… |
|---|---|
absolute | the raw aggregated value (default) |
percentOfTotal | % of the grand total |
percentOfRowTotal | % of its row total |
percentOfColumnTotal | % of its column total |
percentOfParentRowTotal | % of its parent row group, in the same column |
percentOfParentColumnTotal | % of its parent column group, in the same row |
runningTotal | a cumulative running total |
difference | the difference from the previous value |
percentDifference | the % difference from the previous value |
The percent modes are computed on a 0–100 scale. A field without a format
of its own shows them as the locale's percent with at most two decimals —
37.51% in English, %37,51 in Turkish — on screen, in CSV and PDF, and in
Excel (number format 0.00"%"). A format on the field replaces this; the
value it receives is still on the 0–100 scale.
A fixed text beside the number
A currency symbol the locale would put elsewhere, or one that has no ISO code,
goes in the format object as suffix (after the number) or prefix (before
it), next to the usual Intl.NumberFormatOptions:
{ id: 'amount', dataField: 'amount', caption: 'Amount', dataType: 'number',
area: 'data', summaryType: 'sum',
format: { minimumFractionDigits: 2, maximumFractionDigits: 2, suffix: ' ₺' } }
// tr-TR: 1.234,50 ₺ -1.234,50 ₺ 0,00 ₺ (no number: empty)
- The text is written exactly as given, spaces included, after the number
Intlformats in the grid'slocale. Aprefixgoes after the minus sign:{ prefix: '$' }writes-$1,234.50. - Excel gets the number, with the text in its number format:
#,##0.00" ₺","$"#,##0.00. The text is quoted, so characters Excel reads as format codes (0 # % ; @ [ ]) stay literal, and a"in it is written\". The column is made wide enough for the text and the minus sign. - Give
minimumFractionDigits/maximumFractionDigits. Without them the code isGeneral" ₺": Excel writes the number with the decimals it has and no thousands separator (1234.5 ₺where the screen reads1.234,5 ₺). No single Excel code writes Intl's default (grouping, up to three decimals) without leaving a decimal point after whole numbers, so General is the closest. - The cells, their screen-reader text, the header filter list, the charts'
tooltips,
getSummaryTable({ display: true }), CSV, PDF and print write the same text. The footer's selection statistics write their sum, average, minimum and maximum (two decimals, as always) with the text when every selected cell belongs to this field; the count has none, and a selection over more fields has none. - Not carried: the drill-down window lists the source rows without the field's format, and copying cells (Ctrl+C) copies the cell's text, so a pasted "1.234,50 ₺" is text in Excel, not a number. Use the Excel export for numbers.
- To change the text at run time, give the field a new format object with
setFields(or yourfieldsprop); the grid formats with the new one. - It is plain data, not a function, which is why Excel can carry it: a
function
formatreaches Excel as a bare number. Combining it withstyle: 'percent'is not covered. - Right-to-left locales: the text is placed after (or before) the number in reading order, as for any other character; the browser lays it out from there.
Rounding on the binary value
Intl rounds the decimal text of a number. A JavaScript number is a binary
double, and most decimals sit just below or above the text they are written
as: 3227614.15 is stored as 3227614.1499999999068677…. With one decimal
Intl writes 3.227.614,2 (tr-TR), while (3227614.15).toFixed(1), and
any program that rounds the stored value, gives 3227614.1. To show what such
a program shows, put roundBinary: true in the format object:
{ id: 'amount', dataField: 'amount', caption: 'Amount', dataType: 'number',
area: 'data', summaryType: 'sum',
format: { maximumFractionDigits: 1, roundBinary: true } }
// tr-TR: 3.227.614,1 (without roundBinary: 3.227.614,2)
- The value is rounded as
toFixedrounds it: on the stored value, an exact half away from zero (0.5→1,-2.5→-3,1.005→1.00,2.675→2.67). The rounded number is then formatted with the same options, so grouping, the locale,minimumFractionDigits,style: 'currency',prefixandsuffixwork as before. - The number of decimals is the formatter's:
maximumFractionDigits, orIntl's default when it is not given (3 for a plain number, the currency's own digits, 0 for a percent). style: 'percent'is rounded as it is shown, multiplied by 100:0.145(stored0.14499999…) is14%, whereIntlalone writes15%.- With
maximumSignificantDigitsthe value is rounded liketoPrecision. - Left to
Intl, unchanged: values of1e21and more, more than 100 digits, anotationother than'standard'(compact, scientific, engineering), and aroundingPriority,roundingIncrementorroundingModeof your own. A value that rounds to zero keeps its sign, sosignDisplaydecides as it does for the unrounded value (-0.04reads-0by default,0withsignDisplay: 'negative'). - The flag has no effect once the digits go past what a double carries
(about 15–17 significant digits in all): rounding there gives back the same
number, so
3227614.15withmaximumFractionDigits: 15reads3.227.614,15with or without it. The rounding itself works up to 100 digits (toFixed's limit); past that the value is left toIntl. - With
precisionthe total is the number nearest the exact decimal sum, and that number is rounded. - The cells, totals, a number row or column field
grouped by its format, the header filter
list, the footer's selection statistics (with their two decimals), chart
labels and tooltips,
getSummaryTable({ display: true }), CSV, PDF, print and the clipboard export write the same rounded text. - Excel gets the rounded value as a number (
3227614.1) with the number format it gets without the flag (#,##0.0), so Excel, which rounds the decimal text asIntldoes, shows the same digits as the grid. This holds for the pivot and list workbooks, the summary table and the streamed files written for large data. For a percent the written value is the fraction (0.14under0%). - A
style: 'unit'field gets its unit's text in the Excel number format, in the grid's locale ({ style: 'unit', unit: 'day', unitDisplay: 'long', minimumFractionDigits: 1, maximumFractionDigits: 1 }→#,##0.0" gün"intr-TR), with or without the flag. Excel has no plural forms, so a language whose unit word changes with the number (English1 day/2 days) shows one form. In the file streamed for large lists, a flagged column whose format has no Excel code (a plain number with no fraction digits and noprefix/suffix, or a compact, scientific or engineering notation) is written as the rounded text, as without the flag; in the other Excel files a flagged column with no fraction digits getsGeneral, which shows the rounded value as it is. - Without
roundBinarynothing changes — the same text and the same files — except that astyle: 'unit'field now carries its unit into the Excel number format (above); its values are the same numbers as before.
% of the parent total
With nested row fields, percentOfParentRowTotal answers "what share of its
group is this?" rather than "what share of everything?":
// Rows: Region > Country. Each country shows its share of its region,
// each region its share of the grand total.
{ id: 'share', dataField: 'revenue', caption: 'Share of parent', dataType: 'number',
area: 'data', summaryType: 'sum', summaryDisplayMode: 'percentOfParentRowTotal' }
| Row | Revenue | Share of parent |
|---|---|---|
| EMEA | 100 | 50% (of the 200 grand total) |
| EMEA › Germany | 60 | 60% (of EMEA) |
| EMEA › France | 40 | 40% (of EMEA) |
| APAC | 100 | 50% |
| Grand total | 200 | 100% |
- The parent is the immediate parent group on that axis. A top-level group's parent is the grand total, and the grand total itself shows 100%.
- Each column is divided separately: Germany in 2025 is a share of EMEA in 2025.
- A collapsed group shows its own share of its parent; its children are not computed until it is opened.
- Hiding subtotal rows (
showRowTotals: false) changes nothing: the parent's total is still what the share is taken of. percentOfParentColumnTotalis the same rule across nested column fields, within each row.- A parent that totals 0 shows 0.
Grouping
Group date and number fields with groupInterval:
{ id: 'orderDate', dataField: 'orderDate', caption: 'Month', dataType: 'date',
area: 'column', groupInterval: 'month' }
Date intervals: year, quarter, month, week, day. quarter, month
and day gather the same period of every year into one member (every January
together); nest them under a year field to keep years apart.
week is the ISO 8601 week: weeks start on Monday, and week 1 is the week
holding the year's first Thursday. Each member is labelled with its ISO
week-year and number, so years never mix and the members sort in calendar
order:
{ id: 'orderWeek', dataField: 'orderDate', caption: 'Week', dataType: 'date',
area: 'row', groupInterval: 'week' }
// 2026-12-28 → "2026-W53", 2027-01-01 → "2026-W53", 2027-01-04 → "2027-W01"
Like the other intervals, a date is read as the local calendar date it falls on.
Calendar intervals
Three more date intervals keep every year apart, and their members sort in date order:
| Interval | Member | Turkish text | English text |
|---|---|---|---|
yearQuarter | 2026-Q1 | 2026-Ç1 | 2026-Q1 |
yearMonth | 2026-01 | 2026-01 | 2026-01 |
monthWeek | 2026-01-1 | 2026-01-1 | 2026-01-1 |
monthWeek is one row of a calendar whose weeks start on Monday. The row that
holds the 1st of a month is that month's week 1, and the days of the previous
month in that row belong to it as well. So 29–31 December 2025 (Monday to
Wednesday) and 1–4 January 2026 are 2026-01-1, and 5–11 January is 2026-01-2.
A month's last row that holds the next month's 1st is the next month's week 1. It is
not the ISO week of week.
{ id: 'quarter', dataField: 'orderDate', caption: 'Quarter', dataType: 'date',
area: 'column', groupInterval: 'yearQuarter' }
{ id: 'week', dataField: 'orderDate', caption: 'Week', dataType: 'date',
area: 'row', groupInterval: 'monthWeek' }
The member is the same in every language, so a saved filter or an expanded group
still matches when the reader switches language; only a quarter's letter follows
the locale (Ç in Turkish; T in French, Spanish, Italian and Portuguese; Q in
the other languages). The headers, the filter list, the exports and the charts write the
same. getSummaryTable's rows hold the member (2026-Q1);
formatDimensionValue(value, field, 'grid', locale) writes it as the grid does. A
date that cannot be read is a blank. A serverSource receives the interval in its
request and groups on the server, as with any interval.
These are new intervals: quarter, month and week do not change, and neither
do saved states that use them, unless the app opts in. To use the calendar
intervals throughout, set layout.dateIntervalChoices: 'calendar':
- The field settings dialog's Quarter, Month and Week entries pick
yearQuarter,yearMonthandmonthWeek, with the same labels. A field whose definition still has an old interval shows it as its own entry with a sample ("Quarter (Q1)"); OK keeps it, and picking Quarter switches it. - A state that is put back is converted:
applyPersistedState,stateStoring(an asynchronousonLoadtoo), a saved report andsetFields. A date field withquarter,monthorweekgets the calendar interval. Its members change, so what named the old ones is dropped: that field's header filter selection, its label filter, every open group through it, and a summary sort whose path runs through it. Its value filter and the rest of the state come back as saved. The fields the grid starts with (initialFields) are not converted.
This is a setting of the app: it is not saved with the grid's state. React and plain JS.
With a serverSource, the request names the interval and the server groups. The
member keys are: yearQuarter YYYY-Qn (n 1–4), yearMonth YYYY-MM,
monthWeek YYYY-MM-w (w 1–5: the Monday-first calendar row, owned by the month
its Sunday falls in), all from the local calendar date. The grid writes the
quarter's letter itself.
<BasePivotGrid locale="tr" layout={{ dateIntervalChoices: 'calendar' }} />
Numbers take a bucket width as a number: groupInterval: 100 groups into
0–99, 100–199, and so on. The strings numeric and custom have no effect, and
the grid reports them when the fields are set.
Grouping by the formatted value
A number field in Rows or Columns groups on its raw value and writes it raw in
the header, whatever its format. Set groupByFormat: true to group it by the
text the format writes instead, in the grid's locale:
{ id: 'rate', dataField: 'rate', caption: 'Rate', dataType: 'number', area: 'row',
format: { minimumFractionDigits: 1, maximumFractionDigits: 1 }, groupByFormat: true }
// 18.21, 18.23 and 18.24 → one row "18,2" (locale tr-TR), its cells sum all three
The text is the one the field's filter list shows, so the list and the table
agree. One limit: the grid regroups when the format's options or a format
function's source text change, not when a function's behaviour changes through
what it closes over (a digits value in React state, say). Then define the
function anew (different source) or turn groupByFormat off and on. Everything that names a member uses it: the header, exports,
charts, cellClick records and the drill-down, getCellRecords, and the path
keys in expandedPaths and sortBySummaryPath. Members sort by their smallest
raw value, not as text ("9,5" before "18,2" before "1.234,6"); blanks and text
values come last.
The filter stays a set of raw values. To filter to one member from code (a
chart click, a path), pass controller.memberFilterValues(fieldId, member) to
applyFilter; it returns every raw value under that text.
It does nothing without a format, with a groupInterval (the interval already
groups), on a date field, for a field in the Values area, or with a
serverSource: the browser ignores it and the server groups. Your own
serverSource.compute sees groupByFormat on the field objects; the request
pivotServerSource sends does not carry it. Turning it on or off closes that field's open branches, as moving the
field does. The values are formatted once each, while the data is prepared, so
a format function works and large data stays fast.
Field groups (Enterprise)
Fields with the same group move as one: drag one, or move it from the menu
or with changeFieldArea, and the others follow, side by side in one area.
groupIndex orders them (otherwise their order in the field list).
{ id: 'year', dataField: 'year', caption: 'Year', dataType: 'string', area: 'column', group: 'date', groupIndex: 0 },
{ id: 'quarter', dataField: 'quarter', caption: 'Quarter', dataType: 'string', area: 'column', group: 'date', groupIndex: 1 },
Removing one to the field list removes the group. Each member keeps its own chip, sort and filter.
The group is joined inside the change itself, so onFieldsChange hears one
change with the group already together. A group goes only where every
member may sit: if one member's allowedAreas leaves an area out, the whole
group is refused there — controller.canMoveFieldTo says no for each member,
"Move to" and the drag targets follow it, and a setFields that splits the
group into such an area is joined back where the other members are.
onFieldMove (and the fieldMove event) is asked about the field the reader
moved, not separately about the members that follow it. With a controlled
fields prop, a split group you pass in is shown joined and onFieldsChange
is called once with the joined list, so your state matches the screen.
How a group looks
A group is drawn as one unit in every area (filter, rows, columns, values): a small ⊟ button before its first chip and a short line between its chips. In the filter area, which sorts its chips by name, a group sits where its first member sorts, its members side by side after it. Dragging any member shows every member in the drag preview, so you see what moves before you drop. With the keyboard, Ctrl+Arrow (Cmd+Arrow on a Mac) on any member moves the whole group one place.
Collapsing a group
The ⊟ button collapses the group: only its first member stays, and the other members leave the layout until the group is opened again with ⊞. While collapsed, the chip that stays stands for the whole group and writes the group's name (the first member's caption when the group has none); its tooltip and screen-reader name still say which field it is, and sorting or filtering from that chip acts on that first field.
Collapsing never changes the data. A hidden value field's column is gone from the cells, but it is still computed: a value filter, a sort by its totals, a top N or a summary formula that reads it keeps working exactly as when the group is open. A hidden filter-area field's chip is gone, but its filter still applies, and the collapsed filter area's "N filtered" counts it. A hidden row or column field's level is gone from the table (that is the point of collapsing it); a header filter on it still applies, while its own value filter, label filter and top N, which work on its level, rest until the group opens. Resting them changes no total: they choose which members are shown, and a parent's total counts all of its members either way.
When a hidden member filters, the visible chip says so: a dashed line along its top edge, and its tooltip and screen-reader name say "a hidden field of group … is filtered". That mark counts every filter of a hidden member: its header filter, its label filter, its value filter and its top N. A visible chip's own filter mark is, as before, about its own header, label and value filters: its top N shows in the table itself, as fewer rows.
The field list does not list hidden members either, but its search finds them: typing a hidden member's name shows the group's visible member, with the hidden one's name beside it. The button is a real button: Tab reaches it, Enter or Space opens and closes the group, and a screen reader hears "Collapse group KDV" and whether it is open.
A group can start collapsed, and it can have a name. Write them on the group's first member:
{ id: 'vat', dataField: 'vat', caption: 'VAT', dataType: 'number', area: 'data', summaryType: 'sum',
group: 'vat', groupIndex: 0, groupCaption: 'VAT', groupExpanded: false },
{ id: 'vatRate', dataField: 'vatRate', caption: 'VAT rate', dataType: 'number', area: 'data', summaryType: 'avg',
group: 'vat', groupIndex: 1 },
The name (groupCaption) is what the menus, the collapsed chip and the
button's name show. Without one, the group goes by its first member's caption
(the collapsed chip writes what it wrote before) and the menus list it by its
members ("VAT, VAT rate"); the group string is only an id and is never shown.
A group is collapsed when any member says groupExpanded: false.
Letting users change groups
layout.allowFieldGrouping: true adds group items to the chip menu (right
click, Shift+F10, or the "…" button on a touch screen):
- New group… starts a group with this field. It asks for a short name; the field's caption is filled in, and an empty name keeps it.
- Add to group ▸ lists the other groups by name. A group the field may not
join (its
allowedAreasleave out the group's area) is shown, but off. - Remove from group, Rename group… and Ungroup (the members stay where they are, without a group).
The items are off by default, so a grid that does not want its users to regroup shows no new menu items. Groups you defined can be changed too.
Every change is one undo step (undoLayout), goes to onFieldsChange, and is
reported once more as onFieldGroupChange:
<EnterprisePivotGrid
layout={{ allowFieldGrouping: true }}
onFieldGroupChange={(e) => {
// e.action: 'create' | 'add' | 'remove' | 'delete' | 'rename' | 'collapse' | 'expand'
// e.groupId, e.group (null once it has no member), e.fields (the new list)
}}
/>
The same changes from code: controller.changeFieldGroup({ action: 'create', fieldId: 'net', caption: 'Totals' }),
and controller.getFieldGroups() lists the groups with their names, members and
whether they are open. A group made on screen gets the id ~group-1, ~group-2,
and so on: ids starting with ~ are the users' own, so do not start your group
strings with it. Two groups may not share a name: a repeated name gets a number,
"VAT (2)". When a group's first member leaves it (removed, moved to another group,
or gone from your fields), the next member takes over the group's name and its
collapsed state.
A user's groups are theirs: their names, members and open or closed state are
saved with the layout (stateStoring, getPersistedState) and in a saved
report. On a restore, each of these that the user changed comes back for the
fields it names; what the user did not change follows your current
definitions, so a field you added later joins the group you put it in, and a
field you removed is simply gone from its group.
Moving fields
Users move a field by dragging its chip, from its menu ("Move to", "Hide"), from
the field list (its checkbox, "Select all", a drag) and from the keyboard
(Ctrl+Arrow, Delete). Your code moves one with changeFieldArea, showFields,
removeField and moveField.
Allowed areas
allowedAreas limits the areas a field may sit in. Leave it out for any area.
Hiding a field is always allowed.
// An amount is filtered or summed, never a column or a row.
{ id: 'amount', dataField: 'amount', caption: 'Amount', dataType: 'number',
area: 'data', summaryType: 'sum', allowedAreas: ['filter', 'data'] },
// A numeric order number is a row or a filter, never summed.
{ id: 'orderNo', dataField: 'orderNo', caption: 'Order no', dataType: 'number',
area: 'chooser', allowedAreas: ['row', 'filter'] },
Every way of moving a field obeys it:
- Drag: over a disallowed area the drag shows "not allowed", and the drop is refused.
- Menu: "Move to" shows the disallowed areas disabled.
- Field list checkbox: the field goes to the area of its definition (the
areait was given), else the first of itsallowedAreas. Without either, a number goes to the data area and anything else to the rows. - API:
changeFieldAreato a disallowed area does nothing, andshowFieldsuses the same rule as the checkbox.canMoveFieldTo(id, area)andgetFieldHomeArea(id)answer the same questions for your own controls.
setFields and a loaded layout are not checked: your own layout is trusted.
Approving a move
onFieldMove (and controller.on('fieldMove', …)) is asked before every move,
on every path above. It gets the field, its source and target areas and its new
index. Call e.cancel() to keep the field where it is. An async handler holds
the move until it settles.
<BasePivotGrid
onFieldMove={(e) => {
if (e.targetArea === 'column' && e.fieldId === 'customer') e.cancel();
}}
/>
showFields asks once per field and moves the ones you did not cancel.
Dragging on a touch screen
A finger drags a chip only after it holds still on it: 200 ms by default,
touchDragDelay to change it. A finger that moves sooner scrolls the page, so
swiping over the filter area does not move fields. Holding still about 350 ms
longer opens the chip's menu instead; this works on iPhone and iPad, which send
no contextmenu on a long press. A mouse or a pen drags after 8 px.
touchChipTap sets what a short tap by a finger on a chip does: 'sort' (the
default, as a click does), 'menu' (open the chip's menu) or 'none'. A mouse
or a pen always sorts. React and plain JS.
<BasePivotGrid touchDragDelay={300} touchChipTap="menu" />
createPivotGrid(container, { touchDragDelay: 300, touchChipTap: 'menu', /* … */ });
The long press (about 350 ms more after the hold) opens the chip's menu in both renderers. In the plain JS grid the finger's lift after the menu opened is swallowed once, as in React, so it does not click the menu away.
On a touch screen a chip shows no filter and remove buttons: one "…" opens its menu, which filters ("Filter field"), hides and moves the field. In a row header cell, where the name needs the room, there is no "…" either; hold the chip to open the menu. Every chip is at least 44 × 44 px. With a mouse the buttons are where they were.
While dragging
- The drop goes where the pointer is: the chip or the empty part of the area under it. Before or after a chip follows the pointer's side of that chip, and the mark you see is where the field lands.
- With fields in the row area, the empty part of the row header cells is the end of the row area.
- The whole strip over the data columns belongs to the Columns area: past the Columns box (to its right, to its left in a right-to-left grid) a drop goes to the end of the Columns area. The strip is tinted while a field is dragged into that area; the box itself looks as always.
- Near the edge of the field list, its boxes, the area strips or the pivot body, these scroll by themselves. The page around the pivot does not.
- Dropping a field anywhere on the field list's "All Fields" side hides it.
- While the field list is open over the pivot, the pivot under it takes no drops. Opened as a side panel (below), it does.
- A screen reader hears the field's caption and the area's name, in the grid's language.
The field list beside the pivot
By default the field list opens over the pivot. fieldChooserMode="panel"
(React and plain JS) opens it beside the pivot instead, with nothing covering
the pivot: the pivot stays usable, and a field drags both ways — from the list
to any area or row header, and from a pivot chip back to the list, which hides
it.
<BasePivotGrid fieldChooserMode="panel" />
const grid = createPivotGrid(container, { fieldChooserMode: 'panel', /* … */ });
The footer button, ref.openFieldChooser() and ref.closeFieldChooser() (on
the plain JS grid, grid.openFieldChooser() and grid.closeFieldChooser()) open
and close it as before. Its width is the CSS variable
--pivot-chooser-panel-width (320px by default). On a screen 768px wide or
narrower the full-screen field list opens instead; there the list and its four
boxes scroll as one by finger.
Hiding a field from the user
visible: false hides a field everywhere the user could meet it: it is not in
the field list and not in any area, and it is not computed as a row, column or
value or exported. A filter set on it still applies, as for any field outside
the areas. Its area stays as you wrote it, so visible: true (or leaving
visible out) puts it back.
{ id: 'costCode', dataField: 'costCode', caption: 'Cost code', dataType: 'string',
area: 'filter', visible: false }
Sorting
Sort a field's own values, or sort a row/column dimension by a measure:
// Sort Regions by descending Revenue rather than alphabetically.
{ id: 'region', dataField: 'region', caption: 'Region', dataType: 'string',
area: 'row', sortOrder: 'desc', sortBySummaryField: 'revenue' }
sortBySummaryField targets a data field by id. For an order the built-ins
cannot express, supply calculateCustomSort — a comparator that also receives
the two cells being compared.
Top-N
Keep only the leading values of a row or column dimension. topN is applied
after the sort, so it means "top by whatever you just sorted by":
// The ten highest-revenue regions, and nothing else.
{ id: 'region', dataField: 'region', caption: 'Region', dataType: 'string',
area: 'row', sortOrder: 'desc', sortBySummaryField: 'revenue', topN: 10 }
It applies per level: a topN on Region and a different one on Category keeps
the top regions, and within each, the top categories.
Grand totals still cover the whole dataset. A "top 10 regions" view totals all regions, not the ten on screen, so the visible rows will not add up to the total — unless you ask for the remainder:
{ ...region, topN: 10, topNShowOthers: true, topNOthersCaption: 'Other regions' }
topNShowOthers folds everything below the cut into one extra row (or column)
carrying its own figures.
One honest limit:
avganddistinctmeasures are left EMPTY in that row. The remainder is combined from cells that are already aggregated, which is exact forsum,count,minandmax— but an average needs the row counts behind each value and a distinct count needs the values themselves, and neither survives aggregation. Rather than print a plausible wrong number in a total row, those cells stay blank and the grid reports which measures they were through youronErrorhandler.All three of these were declared and read by nothing until 2026-08-27, and this page carried a worked example of the "Others" row before it existed.
Value and label filters
Two more ways to choose which members of a row or column field stay — the ones a spreadsheet pivot calls value and label filters. By the member's total:
// Regions that sold over a million, and nothing else.
{ id: 'region', dataField: 'region', caption: 'Region', dataType: 'string', area: 'row',
valueFilter: { dataField: 'revenue', operator: '>', value: 1_000_000 } }
operator is >, >=, <, <=, =, !=, between or notBetween; the
two range operators take a second bound in value2 (inclusive, either order).
dataField is the id of a field in the data area, and the test reads its
summary — before any summaryDisplayMode, so a percent-of-total view still
filters on the amount.
By the member's caption:
// Cities whose name starts with "an" — Ankara and Antalya.
{ ...city, labelFilter: { operator: 'startsWith', value: 'an' } }
operator is equals, notEquals, contains, notContains, startsWith or
endsWith. The match ignores case unless you set caseSensitive: true, and it
lowercases in the grid's locale, so in Turkish "iz" matches "İzmir". A blank
member reads as empty text.
They run per level, after the sort and before topN, so the two combine
the way the sentence reads: valueFilter over a million plus topN: 3 is "the
top three of those over a million". As with Top-N, the totals keep counting
every member — the subtotals and the grand total do not shrink to the rows
on screen. A parent whose members are all filtered out stays as one row with
its own total. To leave rows out of the figures themselves, filter the source
data instead, with layout.prefilter.
Both filters are kept in the saved state, so a reader's choice survives a
reload, and a change through controller.updateField recomputes straight away.
A filter that cannot be honoured — a dataField not in the data area, an
unknown operator, a missing value2 — leaves the level unfiltered and is
reported through your onError handler, rather than quietly showing nothing.
Readers set them on screen too. The menu of a row or column field (right-click
the field, or Shift+F10 on it) has Filter by condition…, and so does the
button at the bottom of its member list. The dialog has one line for the
caption and one for a total, with the data field to test. None removes that
line. A field with a condition shows the same filled filter icon as one with
members unticked. The dialog keeps a caseSensitive: true your code set; it
does not offer the switch itself.
Filtering
Header filters are built in — click a row/column field header to include or exclude values. You can also seed filters declaratively:
{ id: 'country', dataField: 'country', caption: 'Country', dataType: 'string',
area: 'filter', filterType: 'include', filterValues: new Set(['USA', 'Germany']) }
The list reads as the headers do. Each row of the list is the value's text
in the field's format; values that read the same are one row. A date field
(dataType: 'date') lists its dates as its headers write them: the field's
format when it holds date options ({ day: '2-digit', month: '2-digit', year: 'numeric' } gives 31.03.2026 in tr-TR, and the headers use it too), the
grid's default date text without one, and a month or weekday groupInterval by
name ("March", not 3). Times of one day are one row. The order, the ticks and
the stored filter stay the raw values, so a saved filter keeps working.
Fully keyboard-driven: the filter popup never needs the mouse — start typing to search, use ↑/↓ to move through the values, Space to toggle a checkbox, Backspace to jump straight back to the search box (deleting as you go), and Enter to apply.
The visual Prefilter builder (pre-aggregation, multi-condition) is an Enterprise feature — see Enterprise & licensing.
From code: controller.applyFilter(fieldId, values, 'include' | 'exclude'),
clearFilter(fieldId), and ref.clearAllFilters() (the plain JS grid:
grid.clearAllFilters()) to turn every field's filter — values, value and
label filters — off in one change; the prefilter stays. ref.openFieldChooser()
and ref.closeFieldChooser() open and close the field list from your own
button.
Quick search
search puts a search box in the footer. Typing in it keeps only the row
members whose caption contains the text, with the members above them, so a
customer or an invoice can be found in a long pivot without building a filter:
<BasePivotGrid gridId="sales" data={data} initialFields={fields} search />
The match ignores case and accents — "sao" finds "São Paulo", and in any locale "istanbul" finds "İSTANBUL". A member that matches keeps all its own children. A match deeper down keeps its parents, even ones that are collapsed: the parent stays collapsed as the reader left it, and expanding it shows only the matching children. The search waits for a pause in the typing; Enter searches at once and Escape clears the box.
The search is a view on top of the reader's own filters, not one of them: it
never changes a field's filter, is not saved with the layout or in a report,
and clearing the box gives the previous view back. Like the label filter, it
only decides which rows are shown — subtotals and the grand total keep
counting all the data. It matches the caption as the header draws it, in the
grid's locale: a date grouped by month is found by its name ("Jan", or "Oca" in
Turkish), not by its number, and a blank row by the dictionary's blanks text ("boş"
finds "(Boşlar)"). Text that a cellTemplate draws instead is not
searched. Expand all with a search on expands every member at that level,
the hidden ones too, so clearing the search shows them expanded as well.
From code, with or without the box (grid.setSearchText in plain JavaScript):
gridRef.current?.setSearchText('acme'); // '' clears it
Conditional formatting
Style cells by value with expression rules. Each rule provides a formula
(value, cell) => boolean and a style applied when it returns true:
{ id: 'revenue', dataField: 'revenue', caption: 'Revenue', dataType: 'number',
area: 'data', summaryType: 'sum',
conditionalFormatting: [
{ type: 'expression', formula: (v) => v < 0, style: { color: '#dc2626', fontWeight: 600 } },
{ type: 'expression', formula: (v) => v > 100000, style: { backgroundColor: '#dcfce7' } },
] }
Rules are evaluated top-to-bottom and merged, so later rules win on conflicting
properties. style is a standard React CSSProperties object.
The other three rule types
PivotConditionRule.type offers four kinds, and since @kanunilabs/pivotgrid-core
1.3.0 all four render. The three scale-based ones take their configuration in the same
style object:
conditionalFormatting: [
// A colour scale across the measure's range.
{ type: 'colorScale', style: { colors: ['#f8fafc', '#2563eb'] } },
// An in-cell bar, painted UNDER the value so the number stays readable.
{ type: 'dataBar', style: { color: '#3b82f6', negativeColor: '#ef4444' } },
// A glyph before the value. Cut points are in the measure's own units;
// without them the range is split evenly between the icons.
{ type: 'iconSet', style: { icons: ['arrow-down', 'minus', 'arrow-up'], thresholds: [0, 100] } },
]
Two things are worth knowing:
Totals are excluded from the range. A grand total sits an order of magnitude above the cells beside it; letting it set the top of a colour scale would push every real value into the first stop — correct, and useless.
Only colorScale survives an export. A spreadsheet cell in our writers
carries a fill colour, so a colour scale exports as that colour. A bar and an
icon have no cell-level equivalent, so an exported file keeps the value without
them — and setting one of those rules says so through your onError handler
when the fields are set, once per message.
Note also that the export applies the first matching rule where the screen merges all of them, so a cell with two matching rules can look different in a downloaded file.
A long filter area
With many filter fields the filter area can take the whole pivot.
layout.filterAreaMaxRows caps it at that many rows of chips; past it the
area scrolls inside itself (in React also while a field is dragged at its top
or bottom edge). The button at the end of its title collapses it to one row and
shows how many of its fields filter; that state is layout.filterAreaCollapsed
and is saved with the layout. Neither setting re-runs the pivot.
<BasePivotGrid layout={{ filterAreaMaxRows: 2 }} />
layout.filterAreaCollapsedRows (default 1) is how many rows of chips the
collapsed area keeps; 0 leaves only its header: the name, how many fields
filter, and the button that opens it.
On a screen 768 px wide or narrower the filter area also never takes more than
30% of the pivot's height, whatever filterAreaMaxRows says (a smaller cap
still applies), and scrolls inside itself past that; the Values and Columns
areas above the table headers stop at 88 px and scroll inside themselves. So a
phone keeps room for the first data rows. This needs the pivot to have a
height of its own; a pivot that is as tall as its contents is not capped.
Field chips
Two view settings in layout shape the chips, in React and in plain JS, and
neither re-runs the pivot. showSummaryBadge (default true) shows the
summary-type badge ("Sum") on the value chips; false hides it (the chip's
accessible name still says it). chipMaxWidth (default 120) is the widest a
chip's caption grows, in px: 'none' keeps the whole text, 'auto' sizes the
chip to its caption up to 280 px. A cut caption shows its whole text as a
tooltip.
<BasePivotGrid layout={{ showSummaryBadge: false, chipMaxWidth: 'auto' }} />
layout.textOverflow (default 'ellipsis') says what happens to text that does not
fit: the default ends it with "...". 'clip' cuts it off at the edge instead, on every
field chip (the strips, the field list, the drag ghost) and on the row-header values,
"Total: ..." labels included. Number cells do not change. In 'clip' mode a
row-header value carries its whole text as a tooltip, since there is no ellipsis to
show that it was cut. React and plain JS.
layout.areaChipOverflow (default 'wrap') says what the Values and Columns zones
above the table do when their chips do not fit on one line: by default they start a
second line. 'scroll' keeps one line that scrolls sideways; dragging a field to the
zone's edge scrolls it, and on a touch screen a quick swipe does. 'shrink' also keeps
one line, but narrows the chips in proportion first so that they all fit, with no
scrollbar: the caption is clipped (no ellipsis, whatever layout.textOverflow is; the
chip's tooltip keeps the full name) down to a floor of 56 px (the CSS variable
--pivot-chip-shrink-min, never under 44 px with touch chips), and only a line that does
not fit even at the floor scrolls. The filter area keeps its own row cap
(filterAreaMaxRows). React and plain JS.
'fit' is 'shrink' without the floor and without the scrollbar: the line never
scrolls and no chip is ever cut off. While there is room every chip is at its full
width, caption and buttons whole. Once the line has to narrow, the filter and remove
buttons give way first: no chip in that line draws them (the menu and Alt+ArrowDown
still filter), so the captions keep that width; then the chips narrow in proportion
as far as the zone needs, and the gaps, the chips' side padding and the end drop
target shrink with them. When there is room again, the buttons come back.
The Values zone is as wide as the row-header column, not the window, so with 'fit'
it first takes the free room of the Columns zone beside it: it grows over the start of
the Columns strip to its chips' full width, and the Columns chips move along, at their
own size (a stronger line marks where Values ends, so a drop at the end of Values and
one at the start of Columns stay apart). Only when both together still do not fit do
they shrink: with the Columns zone 'fit' too, both zones by the same factor; otherwise
Values alone, in all the room Columns does not use. Values never gets narrower than the
row-header column, an empty Columns zone keeps room to drop a field on, the two
follow the window as it narrows or widens, and the table's columns do not move. This
works in every rowHeaderOverflow mode. On a narrow phone the chips can still become
too small to read. Hovering anywhere on a chip shows its full
name. A chip too narrow for its filter and remove buttons plus 16 px to grab does not
draw them: it still drags, sorts on a click, and opens its menu on a right click, and
the menu filters (so does Alt+ArrowDown). On a touch screen a chip never goes under
44 px and the line scrolls past that, as in 'shrink'.
One value applies to both zones. To set them one by one, give an object; a zone it does not name keeps the default:
<BasePivotGrid layout={{ areaChipOverflow: { data: 'fit', column: 'fit' } }} />
layout.chipActions sets how the chips in the Values zone show their filter and remove
buttons. It is set for the Values zone only (data); the Columns, Rows and filter
chips keep the inline buttons, and with 'fit' a Columns line that has to narrow drops
them first (above). { data: 'inline' } (the default) is the usual look: the buttons follow the
caption, faint until the pointer is over the chip, and always take their width.
{ data: 'hover' } draws them only while the pointer is over the chip or the chip has
the keyboard focus, on top of the end of the caption, so they take no width and the chip
is that much narrower; nothing moves when they appear. A filtered chip hides them too,
and shows it is filtered when the pointer is elsewhere: its caption is in the danger
colour with a thin danger line along its bottom, which stays visible on a very narrow
chip, and its accessible name ends in "filtered". A chip too narrow for the buttons
draws none, as with 'fit'. The keys are the same in both modes
(Alt+ArrowDown filters, Delete removes, Shift+F10 opens the menu), and on a touch screen
the chip keeps its "…" menu button. Other zones and the field list do not change. This is
a setting of the app: it is not saved with the grid's state. React and plain JS.
<BasePivotGrid layout={{ areaChipOverflow: { data: 'fit', column: 'fit' }, chipActions: { data: 'hover' } }} />
layout.rowHeaderGroupLines (default false) draws a line at the end of every
row-header group, in every row-header column: where a group of several rows ends
(the last row of a group does not repeat its value, and had no line), and between two
subtotal rows in a row. It is the same 1 px bottom border a one-row group already has,
so no row changes height. Either way the row-header cells say where a group starts and
ends (data-group-start, data-group-end), for your own styles. React and plain JS.
layout.rowHeaderToggle (default 'cell') says what opens and closes a row group on a click. By
default a click on the row-header cell, or on a collapsed group's spanning label, selects it and
toggles the group. 'button' makes the cell and the label select only; just the +/− box toggles,
so a user can select a header for Selection Details or Ctrl+C without closing the group. The keys
do not change: Enter, Space, + and − on the focused header still toggle. A click on the box
toggles and selects the group's own cell, as it always did. Column headers already toggle from
the +/− box only, in both modes. On a touch screen (pointer: coarse) the box's hit area is
at least 44 × 44 px in 'button' mode; its drawing and the row height do not change. This
is a setting of the app: it is not saved with the grid's state. React and plain JS.
layout.rowFieldChips (default 'aligned') sets how the row-field chips sit above the row headers
in the tabular layout. 'aligned' keeps today's look: each chip heads its own column and is as wide
as that column, so wide columns leave wide gaps between the chips. 'packed' puts the chips side by
side in one strip across the whole block, with the same small gap as the filter area; the strip wraps
onto more lines when the block is narrow. In 'packed' the columns keep their widths and can still be
resized: each column's grip is drawn on its edge across the strip (double-click fits the column, as
before), but a chip no longer sits over its column, so the grip no longer lines up with a chip's edge.
Every chip is still a drag target (drop before or after another chip to reorder), and the strip itself
is the row area's end target, so a field dropped on the empty part of the strip lands last. The tree
layout already packs its chips, so the option changes nothing there. This is a setting of the app: it is
not saved with the grid's state. React and plain JS.
layout: { rowFieldChips: 'packed' }
Fitting a column to its content
Double-click the edge of a column header (the resize grip) and the column takes the
width of what it holds: the header and the cells that are rendered. Row-header
columns, data columns and a column group all work; the result is reported through
onColumnWidthsChange (React) or kept in the controller's columnWidths, like a
drag. Rows the virtual window has not rendered are not measured, so a long value far
down the list does not widen the column until it scrolls into view and you fit again.
Row headers on a narrow screen
With several row fields the pinned row-header block is held to 60% of the width
and every column is squeezed toward 56 px. layout.rowHeaderOverflow: 'scroll'
keeps each column at its width instead. In React the block stays pinned, is held
to 60% of the width (and always leaves the data at least 160 px, like the
squeeze) and scrolls sideways inside itself. On a desktop its scrollbar is
hidden, so the rows stay in line with the data: scroll it with Shift+wheel or a
trackpad; a finger scrolls it directly. In
plain JS there is one scroller, so the row headers are not pinned and the whole
table scrolls sideways. The default is 'shrink'.
'unpin' lets go of the pin at any width; the grid also lets go by itself when the
columns at 56 px plus 160 px for the data do not fit. Unpinned, the row headers and the
data scroll together in one element, both ways (in React the wrapper with the class
kanuni-pivot-unpinned-scroller): its vertical scrollbar is at the pivot's right
edge, and the header rows stay at the top.
Totals & layout
Grand totals, subtotals and the row-header shape are controlled by the layout
prop (PivotLayoutState):
<BasePivotGrid
gridId="sales"
data={data}
initialFields={fields}
layout={{
showRowGrandTotals: true, // the grand total row
showColumnGrandTotals: true, // the grand total column
showRowTotals: true, // per-level subtotals on the row axis
showColumnTotals: true, // …and on the column axis
totalsPosition: 'bottom', // 'top' | 'bottom', both axes
rowHeaderLayout: 'tree', // 'tabular' (a column per field) | 'tree' (nested)
hideEmptySummaryCells: true, // drop empty rows/columns
dataFieldPosition: 'columns', // where measure captions live
}}
/>
Groups with a single value
A group with one child repeats that child's numbers in its subtotal.
showTotalsForSingleValues: false leaves such subtotals out, as rows and as
columns; showGrandTotalsForSingleValues: false leaves out an axis's grand
total when its top level has only one member. Both default to true, and the
exports follow the same rule as the screen.
layout={{ showTotalsForSingleValues: false, showGrandTotalsForSingleValues: false }}
The coarse form
There is a second, coarser spelling of the same switches — one option per axis pair instead of one per axis:
layout={{
showGrandTotals: 'both', // → showRowGrandTotals + showColumnGrandTotals
showSubTotals: 'both', // → showRowTotals + showColumnTotals
totalsDisplayMode: 'top', // → totalsPosition
}}
These are translated at the controller boundary, so either spelling works. If you pass both, the granular one wins — it is the more specific request.
Column subtotals
Expanding a column group adds a subtotal column carrying that group's own
figure, beside its children — the column-axis twin of the subtotal rows. It
follows totalsPosition, so 'top' puts it before the children.
layout={{ showColumnTotals: true, totalsPosition: 'bottom' }}
It is on by default, like showRowTotals. Set showColumnTotals: false
for the column set you had before this landed.
New in 1.3.0. Before it the option was accepted and reported as unimplemented through
onError. Two things are worth knowing about how it works: the figure is not a second aggregation pass — the engine already totals every visible node, so the subtotal column addresses the group's own value — and it appears in exports too, because the exporters derive their columns from the same list the screen does.All four coarse options were declared and read by nothing until 2026-08-27, and this page used two of them in the example above.
Expand all
The footer's "Expand all" button opens every level of rows and columns at
once. From code, ref.current.expandAll({ allLevels: true }) (or
controller.expandAll({ allLevels: true }) in JavaScript) does the same; a
plain expandAll() opens one more level per call. Each group is opened by its
own path, so the reader can still close one branch afterwards. The worker counts
the groups first and the grid then computes the fully expanded result once (a
serverSource is asked for the whole tree); the open paths then travel to the
worker on every change and into the saved state. So above 5,000 groups, or when that computation fails
(reported through onError), the grid opens everything with the '*'
sentinel instead. One branch can still be closed then: the closed branches are
kept as entries beside the '*' (in the saved state and in the layout undo
too), and a state saved with a bare '*' still means everything open.
"Collapse all" closes everything and clears them.
Opening and closing a branch on a large pivot
Opening or closing one branch redraws only that branch's rows. Under '*'
(after "Expand all", or a saved state with it) the result keeps the members of
a closed branch, so a toggle computes nothing. Without '*', closing a branch
and opening it again computes nothing either, and opening a branch that was
never open computes only that branch. So a toggle on a tree of a million open
rows takes about as long as on a small one.
What your code sees:
- A closed branch's members can be in
rowTree: under'*'always, otherwise after it was closed without a computation. They carryisExpanded: false. ReadisExpanded(orexpandedPaths) to know what is shown, not whether a node haschildren.getCellfor a row inside a closed branch returns its cell. Under'*'colour scales and data bars count those cells too. - A toggle that computes nothing still emits
engineCompleted(in a later task, sotoggleExpanded(key)followed by waiting for the event works). It calls neitheronBeforePivotCalculatenoronAfterPivotCalculate. With either of them set, opening a branch that was never open computes the whole pivot, as before. - A toggle made while a computation is due or running, with a search, or with a running-total or difference display mode, computes the pivot as before.
Engine ids and the index maps
Every node the built-in engine returns has engineId: the row (or column) half
of its cells' key in cellMatrix (rowId * MAX_C + colId).
getEngineResult().rowIndexMap and columnIndexMap still map every path key
to its id, but they are built when first read: on a pivot of a million rows
that takes about a second, and again after each change of the tree (in a live
feed, nearly every batch). To find a cell, use the node's engineId, or
rowIdOf(result, key) / colIdOf(result, key) / nodeIdOf(result, node, isRow)
from @kanunilabs/pivotgrid-core, which walk the tree; '' is the grand total.
Copy a result with copyResult(result, overrides), not with a spread: a spread
reads (and builds) both maps.
Path keys, and open branches after a field change
An open branch is named by a path key: its members joined with |
("EMEA|DE"), the whole pivot being "". expandedPaths,
expandedColPaths, toggleExpanded, sortFieldBySummary's path and the keys of
the engine's nodes all use it. pathKey(['EMEA', 'DE']) builds one and
pathParts('EMEA|DE') reads it back (both from @kanunilabs/pivotgrid-core);
use them instead of join('|') and split('|').
A member whose text is empty (""; only null is "(Blank)") at the first
level has the key "|", and the members under it "||x": a path whose first
member is empty carries one extra leading |. Before, that member got the root's
key and its children lost a part, so opening it could open another member.
Every other key is exactly what it was, so saved state and open paths you stored
keep working; only a path through an empty first member has a new key (the old
one named a different member too). Because a key now always has one part per
level, a check on a saved state can count its levels with
pathParts(key).length. The keys assume member values do not start with or
contain | itself; a value that does can still share a key with another member,
as before.
Open branches and summary sorts belong to the fields they were built from. When
a change of the fields moves one — dragging a field out of the rows, the menu,
the field list, hiding or deleting it, setFields, a controlled fields, undo —
the grid keeps the paths whose leading fields are unchanged and drops the rest.
With rows [Code, BuyPrice] and "A|12.5" open, moving BuyPrice to the
filter area leaves "A" open and removes "A|12.5"; a field sorted by a summary
at a path that no longer exists loses that sort (order included), as does one
whose measure is no longer shown or that left its axis. Paths stored one by
one by an all-levels expand are pruned the same way; the '*' sentinel is never
dropped. The saved state therefore carries no stale
paths, and a state loaded from an older version loses the paths that have more
members than its axis has fields. Undo (undoLayout) puts back what that
change dropped — the paths and the sorts — except where you have set your own
sort since; redo drops them again.
Column widths
Row-header columns start at 150px and data columns at 95px. Long member names
or large totals need more, and defaultColumnWidths sets the starting width
for every column of a kind, however many there turn out to be:
<BasePivotGrid
gridId="sales"
data={data}
initialFields={fields}
defaultColumnWidths={{ rowHeader: 280, data: 120 }}
/>
rowHeader applies to each row-header column — one per row field in the
tabular layout, the single column in the tree layout — and data to each data
column. Either can be left out. The frozen row-header block is still kept
narrow enough to leave room for the data, so in a small container a wide
rowHeader is painted narrower than asked.
A width the user drags beats the default, and is saved with the layout when
stateStoring is on. To set one column from code, use the ref:
const grid = useRef<PivotGridRef>(null);
// Keys: `row-<i>` for row-header column i (0 is the outermost row field),
// `leaf-<i>` for data column i, counted left to right with totals included.
grid.current?.setColumnWidths({
...grid.current.getState().columnWidths,
'row-0': 320,
});
setColumnWidths replaces the whole map, so spread the current one to change a
single column; a column left out goes back to defaultColumnWidths. In the
JavaScript edition the option is the same key on createPivotGrid, and the
method is grid.controller.setColumnWidths.
Export
The footer's Export menu produces CSV, JSON (list / tree / full session
snapshot), XML, Print and Copy to clipboard (tab-separated) in the Community
build. Styled Excel (WYSIWYG Pivot View or flat List View) and PDF export are
Enterprise features — in Community they appear in the menu with an "Enterprise" badge,
and become active when you render EnterprisePivotGrid. Large exports switch to a
streaming writer, and CSV output is sanitized against formula injection.
Cancellation and progress are plumbed through exportData's signal and
onProgress, but the built-in download menu passes neither — you reach them only
through your own PivotGridRef. Row assembly yields between chunks; the three
heaviest calls do not. See Styled Excel & PDF export for
what changes at 100,000 rows and what the file will not match on screen.
Hook onExporting to observe or cancel an export:
<BasePivotGrid
gridId="sales" data={data} initialFields={fields}
onExporting={(e) => { if (!userAllowed) e.cancel = true; }}
/>
Saved views & state persistence
The footer's report menu lets users save, load and set a default named view
(fields + layout). Persist the whole grid state across reloads with
stateStoring:
<BasePivotGrid
gridId="sales" data={data} initialFields={fields}
stateStoring={{ enabled: true, type: 'localStorage', storageKey: 'sales-pivot' }}
/>
Use type: 'custom' with onSave/onLoad to persist to your own backend.
onLoad may return a Promise — an IndexedDB read, a request: the grid starts
on its default layout and switches when it lands, and saves nothing until then,
so the default never overwrites the state being loaded. To open on the stored
layout with no visible switch, read it before mounting and return it as is.
The same state in one piece, from code — for a tab you unmount and rebuild, or a view kept on your server:
const saved = ref.current.getPersistedState(); // versioned plain JSON
// … later, on a new grid:
ref.current.applyPersistedState(saved); // false for another version
It holds the fields and their areas and order, sorting, filters, summaries and
calculated fields, totals and layout options, the chart type, open members and
column widths, and a field's caption, group, groupIndex, groupCaption, groupExpanded and visible
where the reader changed them (only there: a snapshot without them gives the
field your definition back, so a caption you translate later is not frozen by
an old snapshot). Your definition is what you last passed in initialFields,
the fields prop or setFields; the grid's own changes (a calculated field,
a chart cross-filter) are not taken for it. Fields your app no longer defines are dropped on restore — the
calculated fields the reader made stay — and fields added since join as you
define them. A state with another version is refused without an error and the
grid keeps its layout. The plain JS grid has the same pair on the grid itself
(api.getPersistedState(), api.applyPersistedState(saved)), and api.controller has them too.
Two more things travel with it. Parts registered with
controller.registerReportStatePart(key, { get, apply }) — the Enterprise chart
panel keeps its chart this way, and your own chart or side panel can too (call
controller.notifyStatePartChanged() when it changes, so stateStoring saves
it). And the scroll, only when asked for: getPersistedState({ include: ['scroll'] }) or stateStoring={{ …, include: ['scroll'] }}; a restored
scroll is applied once the pivot is drawn.
A large collapsed tree in the saved state
In the React grids and in the Enterprise grids, when more than 5,000 row groups
are closed under "Expand all" (typically the node menu's "Collapse all" on a
large report), the grid keeps the closed rows compactly, and the saved state
(getPersistedState, stateStoring, saved views) holds them as one entry
of expandedPaths instead of one entry per closed group. Measured on 300,000
rows with 906,000 closed groups: about 3.3 MB of JSON instead of 54 MB, and the
state reopens in about a second instead of seven.
- The entry is plain text (base64 behind a control-character prefix), so
JSON.stringify,JSON.parse, IndexedDB,localStorageand text or JSON database columns keep it exactly as it is. - Treat it as opaque: do not edit, split or rebuild it, and pass
expandedPathsback as you received it (applyPersistedState,stateStoring.onLoad,setExpandedPaths). To know which rows are open, readisExpandedon the result's nodes, not the strings inexpandedPaths. - It is restored exactly: every group that was closed is closed, everything else is open (a member that arrived since comes open), and closed groups the current data does not hold (filtered out, another date range) are remembered and come back closed when they appear.
- A save right after opening or closing one branch adds that change to the entry instead of compressing the whole tree again, so saving after every change stays cheap.
- With fewer closed groups the state is saved as before:
'*'and one entry per closed group. getState().expandedPathsis the live set, not a saved state: while the rows are kept compactly it holds'*'and one handle for them. A copy of it (Array.from(...)) given back tosetExpandedPathson the same page restores those rows; stored and read in another session the handle names nothing, every row opens andonErrorsays so. Keep the open rows across sessions withgetPersistedState()orstateStoring.- An entry that cannot be read (cut short or changed in storage, or written by a
newer version) is left out: the report opens with its rows collapsed, the
error goes to
onError, and the rest of the state applies. Nothing throws. - Versions before 1.11.16, and the vanilla Community grid (which does not keep closed rows compactly), open such a state with its rows collapsed. Nothing throws, and the rest of the state applies as usual.
Layout and filters apart
A field's filter is stored inside that field's entry, so to keep the layout and the filters in different places — a layout per customer, filters per period — cut the snapshot in two and put it back together:
import { splitPersistedState, mergePersistedState } from '@kanunilabs/pivotgrid-react';
const { layout, filters } = splitPersistedState(ref.current.getPersistedState());
// later, possibly with another period's filters:
ref.current.applyPersistedState(mergePersistedState(layout, filters));
The plain JS packages export the same two functions (@kanunilabs/pivotgrid,
@kanunilabs/pivotgrid-enterprise), and the script-tag build has them on
KanuniLabsPivotGrid.
filters holds each field's filter and the prefilter; layout holds the rest.
Merging without filters (or with a field missing from it) leaves that field
unfiltered, even where your field definition has a default filter.
Undo and redo of the layout
ref.current.undoLayout() takes back the last layout change and
redoLayout() puts it back; canUndoLayout() / canRedoLayout() (also
getState().canUndoLayout / canRedoLayout) say whether there is a step. A
step is a change of where fields sit, their order, whether they are shown,
their caption or group — from a drag, a menu, the field list or setFields.
Filters, sorting and summaries are not steps and undo leaves them as they are.
The last 20 steps are kept; applyPersistedState and loading a saved view
start over, and clearLayoutHistory() empties the history. The grid binds no
keys: wire your own Ctrl+Z and Ctrl+Y. A caption, group or visibility that
was your definition when the step was taken comes back as your definition is
now, so undoing past a setFields that translated the captions keeps the
translation.
<button disabled={!canUndo} onClick={() => ref.current?.undoLayout()}>Undo</button>
The plain JavaScript grid has the same four on the grid: grid.undoLayout().
Adding or deleting a calculated field is not a layout step (it writes none, and
deleting one cannot be undone); placing it in an area is. undoLayout() and
redoLayout() keep the focus where it was: in the pivot it stays in the pivot,
and on the button that asked it stays there, or moves to the pivot when the step
disabled that button.
Theming & striping
The grid is themed entirely with CSS variables. Colour schemes, dark, the
typeface and the full list of variables are on Theming.
Pass a theme object, or toggle zebra striping with striped:
<BasePivotGrid
gridId="sales" data={data} initialFields={fields}
striped
theme={{ primary: '#0284c7', surfaceHeader: '#e0f2fe', border: '#bae6fd' }}
/>
surfaceHeader and textHeader colour the panels — the filter area, the field
areas, the footer, dialog headers — and, unless you say otherwise, the column
headers too. For a dark header band over light panels, give the band its own
pair:
theme={{ surfaceHeader: '#f1f5f9', headerBackground: '#1e293b', headerText: '#f8fafc' }}
Try the presets live in the Theming playground.
Colour schemes
Both packages ship 36 ready-made colour schemes, light and dark, each one a small stylesheet next to the grid's own. Browse them, or make your own from any of them, in the Theme Builder — it previews the pivot table and exports the stylesheet. In a shadcn/ui app the grid can take your shadcn theme instead, dark mode included — see Tailwind CSS and shadcn/ui. Import the one you want and name it by its id:
import '@kanunilabs/pivotgrid-react/styles.css';
import '@kanunilabs/pivotgrid-react/themes/graphite.css';
<BasePivotGrid gridId="sales" data={data} initialFields={fields} palette="graphite" />
(palette is the same prop the DataGrid takes; theme={{ id: 'graphite' }}
does the same.) The id is all the grid needs: it marks the grid root with data-theme, and
every popup it opens (field menus, the filter list, dialogs, the field chooser,
the drill-down) carries the same mark, so the scheme reaches all of them.
themes/all.css holds every scheme at once, for an app that lets its users
choose. The plain JavaScript package has the same files:
import '@kanunilabs/pivotgrid/styles.css';
import '@kanunilabs/pivotgrid/themes/graphite.css';
createPivotGrid(host, { data, initialFields: fields, theme: { id: 'graphite' } });
A scheme and your own colours combine: anything you set in the theme object
wins over the scheme, so a scheme can be the starting point for a brand colour:
<BasePivotGrid … theme={{ id: 'graphite', primary: '#f59e0b' }} />
Without an id, or with an id no imported stylesheet knows, the grid keeps its
default look. A chart drawn with ChartFactory beside the grid follows the
scheme when you wrap it in <PivotThemeProvider theme={{ id: 'graphite' }}> and
pass palette="theme", which derives the series colours from the scheme's
accent.
Density
density sets the row rhythm. It changes no colours, so it combines with any
theme or scheme:
<BasePivotGrid gridId="sales" data={data} initialFields={fields} density="compact" />
density | Rows | Also |
|---|---|---|
'compact' | 24px | Type one size smaller; for screens that need the most rows. |
'normal' (default) | 28px | The grid as it has always looked. |
'comfortable' | 36px | Larger targets on the toolbar buttons. |
'touch' | 45px | Every cell, header +/- box and filter funnel a full 44px target, for a touch screen. |
Header rows follow the same height. Menus, the filter list and dialogs keep
their size in every density. Changing the prop repaints in place, without
re-running the pivot engine. In the plain JavaScript package, pass density in
the config and switch it later with grid.setDensity('comfortable').
Localization & RTL
Twelve locales ship in the box; ar flips the layout to RTL automatically. See
the Quick start and the
Localization playground.
Performance
Built-in aggregation runs in a Web Worker over columnar storage with a trie-based grouper, so the UI stays responsive on a million rows — try the Big Data Performance playground (100 → 1,000,000 rows). The worker is compiled into the package and started from a Blob URL, so there is nothing to configure in any bundler:
<BasePivotGrid data={data} initialFields={fields} />
A strict Content-Security-Policy is the one case that still needs attention — see Installation.
Too many columns
A field with a different value on almost every row — an invoice number, a
timestamp — dragged onto the columns would make tens of thousands of them, and
drawing their headers would freeze the page. The grid draws the first
maxColumns column members (1,000 by default) and says above the table how
many of how many it shows, suggesting to move the field to the rows or filter
it:
<BasePivotGrid data={data} initialFields={fields} maxColumns={500} />
Only the columns are cut, not the data: the row totals and the grand total
still count every row, and the rows are all there. maxColumns={0} (or
Infinity) turns the cap off. getEngineResult().columnsTruncated reports
{ shown, total } when it applies. Expand all expands the columns past the
cap as well.
The cap is for the screen only: no export is cut. An export of the current
view keeps the rows and the expansion on screen but has every column, so its
columns add up to the row totals; an export with expandAll is computed afresh
and keeps every column too. The file can therefore be much wider than the grid.
Scrolling a long table
The body draws only the rows in view and a few more. Dragging the scrollbar to
the end, or a fast fling, can show the body blank for a moment: the browser
scrolls first and the rows are drawn a frame later. layout.virtualization
changes that, in React and plain JavaScript alike; with no setting nothing
changes:
<BasePivotGrid
data={data}
initialFields={fields}
layout={{ virtualization: { mode: 'auto', threshold: 2000, placeholderRows: true, overscanY: 20 } }}
/>
mode—true(default) draws a window of rows;falsedraws every row at once;'auto'draws every row while there are at mostthreshold(default 2,000), a window above that. The count is the rows the table shows, not the source rows: subtotal rows and the grand-total row count too, and expanding or filtering can cross the threshold. Drawing every row means no blank area ever, but a table of tens of thousands of rows then takes seconds to draw and the page freezes meanwhile, again on every expand, collapse, sort or filter: keepfalseto tables you know are small, or use'auto'. With more than 40 data columns the columns stay windowed, so each sideways scroll step then redraws every row too.placeholderRows— while the rows scrolled into view are not drawn yet, their place shows row-height lines in the row headers and the data instead of a blank area (most useful for a jump to the end). The colours are the CSS variables--pivot-placeholder-row-line(default--pivot-border) and--pivot-placeholder-row-bg(default transparent).overscanY— rows drawn beyond the view, above and below alike (a row only partly in view counts as in view). Not set, the margin is the one of before (about 5 rows each side in React, 5 above and 10 below in plain JavaScript). A value that is not a finite number of 0 or more is ignored, as is such athreshold.
Only rows: past 40 data columns the columns are still drawn in a window,
whatever mode says. The setting can change on a live grid (setLayout, or a
new layout prop); the body is redrawn, the data is not recomputed. (In
DataGrid, virtualization is read only when the grid is created.) The setting
is the app's: it is not saved with the state, and a restored state keeps the
grid's current value.
Live updates
A dashboard that receives rows as they change does not have to hand the grid a
new data array every time. applyTransaction adds, updates and removes rows
without a rebuild: only the rows in the transaction are encoded and sent to the
worker, which regroups them and recomputes the groups they touched.
const grid = useRef<PivotGridRef>(null);
<BasePivotGrid ref={grid} gridId="desk" data={trades} rowKey="id" initialFields={fields} />
// on every message from the feed
grid.current?.applyTransaction({
update: [{ id: 'T-1042', desk: 'Rates', pnl: 18250 }],
add: [{ id: 'T-1043', desk: 'FX', pnl: -400 }],
remove: ['T-0999'],
});
In JavaScript the call is on the grid itself, grid.applyTransaction({ … }),
with rowKey in the createPivotGrid options.
- Rows are matched by
rowKey— a field name, or a function returning a string or number. Without it rows are matched by object identity: update with the very object that is in your data, changed in place, and remove by passing rows rather than keys. - An update for a key the grid does not have is ignored, a remove wins over an update of the same row, and added rows go to the end — the same rules as the DataGrid's transactions.
- It returns what it applied,
{ added, updated, removed }, andgetRawData()returns the new rows at once; the recomputed pivot follows a moment later (theengineCompletedevent, or the next render). - The result is the pivot a rebuild from the new rows would show: the same groups, totals, filters, sorting and custom summaries. The totals a change touches are summed again from their rows, not adjusted by the difference, so decimal totals do not drift over thousands of updates.
- Re-rendering with the same
dataarray keeps the changes. A new array replaces every row, as before. - A transaction that arrives while the grid is still building, or while a field is being moved, is applied as soon as that finishes — in order, without starting the build again.
Measured on 2026-10-03 over a million rows (three grouping fields, two measures; a transaction of 10 updates, 5 removes and 10 adds, in Node 24): about 17 ms of worker time per transaction against 230–290 ms to rebuild there, and about 35 ms on the main thread against 160 ms to encode every row again. Most of that main-thread time is finding the changed rows by key, which is one pass over all rows.
Two things to know. The first transaction on a grid prepares the engine for
the ones after it with one regrouping of the stored data (about 0.3 s at a
million rows), without encoding anything again. And a value that no longer
occurs in any row stays in the engine's dictionary until the next full build —
a new data array, setData or Refresh.
Feeds that tick many times a second
Every applyTransaction finds its rows by key in one pass over all rows and
sends the worker its own message. A feed that calls it a hundred times a second
pays that a hundred times for one picture. Queue the ticks instead:
<BasePivotGrid ref={grid} rowKey="id" asyncTransactionWait={50} /* … */ />
// on every message from the feed
grid.current?.applyTransactionAsync({ update: [tick] });
Queued transactions are merged and applied together once asyncTransactionWait
milliseconds (default 50) have passed since the first of them. The optional
second argument is a callback that runs when its batch has been applied.
flushAsyncTransactions() applies the queue at once, and
controller.getPendingAsyncTransactionCount() says how many transactions wait.
- The merged batch leaves the rows that applying each transaction in order
would. An add followed by an update is one add of the latest row; an add
followed by a remove leaves nothing; the last update of a row wins; a remove
drops an earlier update. Inside one transaction, "remove
7, add7" is a replacement. - The order of your calls is kept. A synchronous
applyTransaction,setDataor a newdataarray applies the queue first. - Destroying the grid drops the queue without applying it.
In JavaScript the calls are on the grid, grid.applyTransactionAsync(…) and
grid.flushAsyncTransactions(), with asyncTransactionWait in the
createPivotGrid options. Measured on 2026-10-08 over a million rows in Node 24:
finding the rows for 100 single-row ticks took about 1.7 s one by one and about
24 ms merged, and the worker received one message instead of a hundred.
The pivot after a batch is computed as often as its cost allows: the grid
measures what the last result cost the main thread (to its first drawn frame)
and waits until that is about 2.5 % of the time. A small pivot is computed after
every batch, as before; a fully expanded one of 200,000 rows near the end of a
feed every half minute or so, while every batch still reaches the worker at
once. flushAsyncTransactions() (also when the queue is already empty),
applyTransaction(), setLoading(false) and an export compute without waiting.
While a batch computes over a result already on screen, the grid keeps that
result up: it shows no loader and isBuilding stays false; isComputing is
true until the newer result is in.
Blank values
A row or column value that is null or missing is one member, the blank member.
It is written with the blanks text of the grid's language ("(Blank)",
"(Boşlar)", "(Leer)"...) everywhere it is shown: row and column headers, subtotal
labels, the filter list, the pivot's Excel, PDF, print and clipboard headers,
chart categories and the drill-down title. Reword it through the dictionary:
dictionary={{ blanks: '(none)' }}. An empty text is allowed,
dictionary={{ blanks: '' }}: the header cell is then empty and the filter list
shows an empty row that can still be ticked; a screen reader reads the
language's own blanks text for that row, and the search box does not match it.
The text is only what is shown. Inside, the member is '(Blank)' (exported as
BLANK_MEMBER from @kanunilabs/pivotgrid-core): filters store it, path keys
and rowPath / colPath carry it, and saved state keeps it, so a saved filter
on blanks opens the same in any language. The list export writes source rows,
where a blank stays an empty cell. In 1.11.8 and earlier every language showed
"(Blank)"; pass dictionary: { blanks: '(Blank)' } to keep that.
No rows
With no rows, from data={[]}, setData([]) or a feed that has not sent
any yet, the grid says so with the emptyData text of its language ("No Data
Found", "Veri Bulunamadı") instead of a loader. While an
applyTransactionAsync batch is queued the loader stays: rows are on their way.
Change the text through the dictionary: dictionary={{ emptyData: 'No sales yet' }}
(createPivotGrid(el, { dictionary }) in JavaScript). getState().noData is
true while the empty text is shown. A server-side pivot always asks its
server and draws the answer, empty or not.
If you mount with data={[]} and fill the grid with applyTransactionAsync
after a fetch, the empty text would show while the fetch is pending. Say the
rows are on their way with loading: the loader shows instead and
getState().noData stays false. A result already on screen stays. Exports do
not wait for loading, only for a change still computing.
<BasePivotGrid data={[]} loading={!loaded} … />
In JavaScript pass loading: true to createPivotGrid and call
grid.setLoading(false) when the last chunk is in; the controller has
setLoading and isLoading too.
Toolbar customization
Show or hide individual footer controls with the toolbar prop:
<BasePivotGrid
gridId="sales" data={data} initialFields={fields}
toolbar={{ showExportButton: true, showCalculatedFields: false }}
/>
Looking for calculated fields, charts or drill-down? Those are in the Enterprise package. For every prop and type, see the API Reference.
Missing a feature? Tell us
The grid grows out of real-world requests — if something you need is missing, awkward, or plain broken, we genuinely want to hear it. Write to [email protected] or use the contact form; license holders can also open a support ticket. Every message is read and answered.