SpreadsheetGrid
Guides

Tree data

Turn flat rows into a parent-child hierarchy with treeData, with open / close, parent aggregates, and filtering and sorting within siblings

With treeData, flat rows become a tree by the parent row's key, giving a hierarchical table you can open and close (since 1.9.0). Use it for tables where parent rows are data rows themselves, such as departments and sections, folders and files, or projects and tasks. Tables that group rows by value (per region, per rep) are row grouping.

Demo (department hierarchy > budget and headcount)

Rows 20 of 20Columns 4 of 4Sort: —
#
1
2
5
8
9
10
11
Rows 20 of 20Columns 4 of 4
Cell —Range —0 cells / 0 rows0 columns
  • Open and close with the mark (▸ / ▾) in the Department column. Select a cell in the Department column and open with Alt+Shift+↓, close with Alt+Shift+↑ (Option on Mac).
  • People and Budget use aggFunc: 'sum', and rows with children (head office, divisions, departments) show the total of the sections below. Those cells can't be edited. Changing a section's value changes the parents' totals too.
  • Type text in the top bar's global filter (for example "Osaka"), and only the matching rows, the rows below them and their parents remain. Parents that don't match are in faint text, and totals cover only matching rows. Searching for a department name shows all of its sections.
  • Sorting by the Budget column orders within siblings (parents move with their children, and rows with children are compared by their totals).
  • Find with Ctrl+F (⌘F on Mac) also matches rows inside closed parents, and opens the parents when moving to that result.
  • "Show CSV (indented)" is exportCsv({ treeIndent: true }). Rows inside closed parents are output too.

Usage

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

type Dept = { id: string; parentId: string | null; name: string; budget: number };

const columns: GridColumn<Dept>[] = [
  { key: 'name', title: 'Department', width: 220 },
  { key: 'budget', title: 'Budget', width: 120, align: 'right', aggFunc: 'sum' },
];

const [rows, setRows] = useState<Dept[]>(initialRows);

<SpreadsheetGrid
  rows={rows}
  onRowsChange={setRows}
  columns={columns}
  rowKeyGetter={(row) => row.id} // the same values as the parent keys. Required
  treeData={{ getParentKey: (row) => row.parentId, column: 'name' }}
/>;
OptionContents
getParentKeyA function returning the parent row's key (the rowKeyGetter value). null / undefined / an empty string '' mean a top-level row. Keys are compared with ===, so return the same type as the row keys (the number 1 and the string '1' are different keys; rows differing only in type are named in a development warning). The tree shape is rechecked when the rows array changes, so when you replace only getParentKey or rewrite a row's parent in place, pass rows as a new array too
columnThe key of the column that shows the indent and the open / close mark (a development warning if it isn't in columns)
defaultOpenDepthHow deep to open at first. Default 'all' (everything open). 1 opens only the top-level rows (two levels visible), and 0 shows only the top-level rows. It applies to rows not opened or closed by hand, and rows added later open or close to this depth too. Changing it after mount reapplies it to rows not opened or closed by hand. Moving a row to another parent keeps the open state decided by the depth when it was first seen
  • rows stays a flat array. Children can come before or after their parents. The order under the same parent is the order in rows.
  • Rows whose parent key isn't in rows go to the top level (one warning in development).
  • Rows whose parent chain leads back to themselves (cycles): among the rows in the cycle, the parent of the one earliest in rows is cut and that row goes to the top level (the others line up below it, so an unedited row may surface at the top. One warning in development). In tables where the parent column can be edited, stop it with validate as in "Stopping cycles" below.
  • It works when there is a rowKeyGetter and the table is clientSide (rows passed with rows). Without rowKeyGetter, it stays a flat table and warns in development.
  • With /lite, add treeDataFeature (Choose the features you bundle).

Open and close

  • Press the mark, use Alt+Shift+↓ / Alt+Shift+↑ in a cell of the tree column, or the handle's setTreeRowOpen(rowKey, open) / expandAllTreeRows() / collapseAllTreeRows() / revealRow(rowKey). Enter starts editing, so it isn't used for opening and closing.
  • revealRow(rowKey) opens closed parents and scrolls to that row (to show a row from a search result or a link). revealRow(rowKey, { columnKey }) also selects that column's cell (to edit an added row right away and so on; even in the same code that added the row, it selects after rendering).
  • Opening and closing apply on the next render, so right after revealRow or setTreeRowOpen in the same code, getViewRowIndex(rowKey) of a row that was closed is still -1. To select that row, pass columnKey, or read it after flushSync(() => grid.revealRow(key)) in React or after grid.revealRow(key) followed by flush() in Solid.
  • The active cell and selection follow their rows when opening and closing. Ones on rows hidden by closing move to the closed parent.
  • onTreeRowOpenChange({ rowKey, open }) is called for each row opened or closed by the mark, keys, setTreeRowOpen, revealRow, ctx.tree.setOpen in renderCell, or moving between find results (not when the state is unchanged). It isn't called by expandAllTreeRows / collapseAllTreeRows / applyState. It's called for opening and closing while filtered too, but those return to their previous state when the filter is cleared. Save the open state with closedTreeRows from onStateChange, not with this notification's arguments ("Saving the open state" below).
  • Parents opened for a result reached while typing in find (Ctrl+F) close again when moving to the next result (parents opened by Enter / next / previous stay open).
const gridRef = useRef<SpreadsheetGridHandle<Dept>>(null);

gridRef.current?.collapseAllTreeRows();
gridRef.current?.revealRow('dev-platform-2'); // open the parents and scroll
gridRef.current?.setTreeRowOpen('sales', false);

Saving the open state

Closed parents go into getState().closedTreeRows (an array of row keys), and opening and closing also call onStateChange. Restoring with closedTreeRows of initialState / applyState closes the listed rows and opens the others (Saving and restoring state). defaultOpenDepth is how it opens at first when there is no saved state.

<SpreadsheetGrid
  // ...
  treeData={{ getParentKey: (row) => row.parentId, column: 'name', defaultOpenDepth: 1 }}
  initialState={saved ?? undefined} // start with saved.closedTreeRows if present
  onStateChange={(state) => localStorage.setItem('dept-grid', JSON.stringify(state))}
/>
  • After closedTreeRows is restored, only the listed rows are closed and the others are open (rows added later open too; defaultOpenDepth applies only when there is no saved state).
  • Listed keys of rows that don't exist yet or have no children are remembered too, and when that row later becomes a parent it starts closed (useful on screens that load rows later). But getState() only shows parents closed now, so saving before the rows arrive loses the open state. Save after the rows arrive.
  • In large trees with a small defaultOpenDepth, there are many closed parents, and the saved state grows (about 80KB for 10,000 parent rows).

Parent row values and aggregates

  • By default, parent rows show their own values (parents are data rows too, so they can be edited like any other row).
  • Only for columns with aggFunc, cells of rows with children show an aggregate of the leaf rows below (rows without children). Aggregates and formats are the same as row grouping ('sum' / 'avg' / 'min' / 'max' / 'count' / a function; aggregates other than sum show the kind in small text before the value).
  • Cells showing aggregates are read-only (excluded from editing, paste, fill and Delete). Copy and export use the aggregate value, and find and selection aggregates don't count them.
  • A parent row's own value isn't counted in the aggregate. As in the example above, leaving aggregate columns of rows with children at 0 or empty keeps the data clear too (when you want intermediate parents' values added too, like "payroll of everyone under them" in an org chart, the built-in aggregates can't do it).
  • Aggregate cells get .ssg-body-cell--tree-aggregate, and ctx.tree.aggregate in cellClassName / renderCell is true. They look the same as row grouping aggregates; to show that they can't be edited, put a color on this class ("Look" below).
  • Column filters on aggregate columns are decided by the parent row's own value. If you leave parent values empty, "(Blank)" appears among the options, and choosing it matches the parents. To keep users from filtering by an aggregate column, don't put filterType on it.

Ratio columns (actual ÷ budget)

A getValue computed column is a per-row value, so in rows with children it's computed from the parent's own values (empty and so on). To show ratios on parents and the total row, make aggFunc a function and compute from the rows below (rows = the leaf rows under that parent).

{
  key: 'rate',
  title: 'Achieved',
  getValue: (row) => (row.budget ? row.actual / row.budget : null),
  aggFunc: ({ rows }) => {
    const budget = rows.reduce((sum, row) => sum + (row.budget ?? 0), 0);
    return budget ? rows.reduce((sum, row) => sum + (row.actual ?? 0), 0) / budget : null;
  },
  valueFormatter: ({ value }) => (typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : ''),
}
  • Even with aggFunc on the tree column (column), rows with children show their own values (for showing a count in the total row and so on).
  • The total row (totalRow) aggregates leaf rows only (so nothing is counted twice with the parent aggregates).

Filtering and sorting

  • Filtering: column filters and the global filter treat the matching rows and all rows below them as matches, and also show their parents (searching for a department name shows all of its sections; the same as AG Grid's default). Parents that don't match are in faint text (.ssg-body-row--tree-unmatched on the row). The count in the bottom bar is the number of matching rows (including the rows below matching rows).
  • Parents up to matching rows are opened to show them (they can be closed by hand). Rows below matching rows keep their current open state. Opening and closing while filtered is temporary; clearing the filter returns to the state before filtering.
  • While filtered, parent aggregates cover only matching rows (all rows below a matching parent are matches, so that parent's aggregate is the same as before filtering).
  • Sorting: rows are sorted among siblings under the same parent. Parents move with their children. When sorting by an aggregate column, rows with children are compared by their aggregate values.

Editing, selection and copy

  • Selection, editing, copy, paste and fill work as before on the order of visible rows. Rows inside closed parents aren't included in ranges.
  • The edit input in a cell of the tree column starts to the right of the indent and the mark.
  • Select all in row selection (enableRowSelection) covers all rows matched by filters (including rows inside closed parents and rows below matching rows, but not parents that don't match).
  • To add or remove rows, just change rows. If an added row's parent is closed, the row goes inside it (revealRow can show it). To change a parent, rewrite the row's parent key value (there's no reparenting by dragging).
  • When opening and closing, the active cell and selection follow their rows, but when rows changes (new rows arrive at the top, rows are removed, reparenting moves rows, paste or fill rewrites the parent column), the default activeCellFollows="position" stays at the position and may point at another row. For tables whose rows increase and decrease, or whose parent column can be edited, we recommend activeCellFollows="row" (Cell editing).
  • Together with change tracking (trackChanges), when a closed parent contains unsaved rows, that parent's row number shows the unsaved dot too (read as "Has unsaved changes inside"; opening moves the dot back to the edited rows).

Stopping cycles

In tables where the parent column can be edited, stop rewrites such as making someone's report their manager with validate (with 'reject' it isn't committed; Validation).

// walk up from the new parent (value); reaching yourself (row.id) means a cycle.
const wouldCycle = (byId: Map<string, Employee>, id: string, parentId: string | null) => {
  for (let current = parentId; current !== null; current = byId.get(current)?.managerId ?? null) {
    if (current === id) return true;
  }
  return false;
};

{
  key: 'managerId',
  title: 'Manager',
  editable: true,
  validate: ({ row, value }) =>
    wouldCycle(byId, row.id, (value as string | null) ?? null) ? "A report can't become the manager" : true,
}

Find (find)

Find in cells also matches rows inside closed parents. When moving to a result, that row's parents are opened (onTreeRowOpenChange for each opened row). Parents opened for a result reached while typing close again when moving to the next result.

Export

  • Scope 'view' outputs the rows shown (rows matched by filters and their parents) from parents down, regardless of open state (rows inside closed parents are output too).
  • treeLevels of getExportData() holds each row's depth (top = 0) (for indents or outlines in Excel).
  • The tree column in CSV isn't indented by default. exportCsv({ treeIndent: true }) adds one full-width space per depth; passing a string puts that string in front once per depth.
grid.exportCsv({ treeIndent: true });
// Department,Budget
// Head office,600
//  Sales,300
//   Section 1,100

grid.exportCsv({ treeIndent: '- ' });
// Department,Budget
// Head office,600
// - Sales,300
// - - Section 1,100

Using tree information in renderCell

ctx.tree of cells in tree-data rows holds { level, hasChildren, open, aggregate, setOpen } (ctx.tree of cellClassName / cellNote is { level, hasChildren, open, aggregate } without setOpen). In aggregate cells of rows with children, aggregate is true and ctx.value is the aggregate. In the tree column, the grid draws the indent and the mark, and renderCell draws the contents to their right.

hasChildren is whether there are visible children. Empty folders and rows whose children were all filtered out are false. To change icons or weight by kind of row, like folders and files, decide by the row's data (row.kind below and so on).

{
  key: 'name',
  title: 'Department',
  width: 240,
  renderCell: ({ row, value }) => (
    <span style={{ fontWeight: row.kind === 'dept' ? 600 : 400 }}>{String(value)}</span>
  ),
}

Screen readers and keyboard

  • The table body is role="treegrid". Rows get aria-level (top = 1), aria-setsize / aria-posinset (the number of siblings and the position among them), and rows with visible children get aria-expanded.
  • The open / close mark is a button named "Expand (row name)" / "Collapse (row name)" (expandTreeRow / collapseTreeRow in localeText; the defaults are Japanese, see English and text). The name is the tree column's text with surrounding spaces removed; for empty rows it's "Expand Row 3" (treeRowNumber). It isn't in the Tab order (with the keyboard, use Alt+Shift+↓ / ↑).
  • Alt+Shift+↓ / ↑ work only in cells of the tree column (in other columns they extend the range like Shift+↓ / ↑). Even with a range selected, only the active cell's row opens or closes.
  • Parents that don't match a filter are distinguished by color only. In Windows high contrast (forced-colors), the text of those rows is the system's dim text color (GrayText).

Look

NameContents
--ssg-tree-indentThe indent per depth (default 16px)
--ssg-tree-unmatched-textText color of parents that don't match a filter
.ssg-tree-cellCells of the tree column
.ssg-tree-toggleThe open / close mark (aria-expanded="true" when open)
.ssg-body-row--tree-unmatchedRows of parents that don't match a filter
.ssg-body-cell--tree-aggregateAggregate cells of rows with children (a marker that doesn't change the look)
[data-ssg-tree-level]The row's depth (top = 0)
.my-grid {
  --ssg-tree-indent: 20px;
}
/* make top-level rows bold */
.my-grid .ssg-body-row[data-ssg-tree-level='0'] .ssg-tree-cell {
  font-weight: 600;
}
/* aggregate cells can't be edited, so make their text subdued */
.my-grid .ssg-body-cell--tree-aggregate {
  color: var(--ssg-readonly-text);
}
  • In the design system themes (themes/*.css), the text of parents that don't match is the theme's subdued text color moved a little toward the body text (4.5:1 or more on white).
  • On touch devices (pointer: coarse), the open / close mark keeps its visual size but its pressable area extends in all directions (the same for row grouping and detail row marks).

Auto-sizing columns (autoSizeColumns or double-clicking a header border) adds the width of the deepest indent and the mark among visible rows to the tree column.

What works together

It works together with pinned columns, column groups, pinned rows, the total row, autoHeight, conditional formatting, change tracking, the searchable select editor and detail rows (detailRow).

  • Detail rows: the detail band goes below its row (between the parent row and its children); closing the parent hides the children's bands too, and opening brings them back. The detail row mark and the tree mark are the same ▸ / ▾, so to tell them apart, remove the detail row's own column (showToggleColumn: false) and put your own button (such as "Details") that calls ctx.detail.toggle in any column's renderCell ("Placing the toggle yourself" in Detail rows).

Large trees

In a tree of 200,000 rows, every added row or edited cell rebuilds the tree shape and the parent aggregates (about 0.1–0.4 seconds each in a production build; 2–4 times a flat table). For tables where new rows arrive often, batch the arrived rows into rows every few seconds. Fewer aggregate columns (aggFunc) make it faster.

What doesn't work together

  • rowGroup (row grouping), labelRow (label rows) and enableRowDrag (row drag) don't work together with tree data (tree data is used, with a warning in development).
  • Tree data doesn't work with serverSide (dataSource) (a warning in development). Loading children from the server later isn't in the first version.
  • Not in the first version: reparenting by dragging, selecting children together by checking a parent, and building from nested children arrays. Flatten nested data and add parentId before passing it.
type Node = { id: string; name: string; children?: Node[] };
const flatten = (nodes: Node[], parentId: string | null = null): (Node & { parentId: string | null })[] =>
  nodes.flatMap((node) => [{ ...node, parentId }, ...flatten(node.children ?? [], node.id)]);

Full tables of the handle and props are in the API reference.

On this page