Skip to content

Tree Data Grid

Source code
import '@revolist/ui/styles.css';
import { defineCustomElements } from '@revolist/revogrid/loader';
import {
ExportExcelPlugin,
TREE_COLLAPSE_ALL_EVENT,
TREE_EXPAND_ALL_EVENT,
TREE_STATE_CHANGED_EVENT,
} from '@revolist/revogrid-pro';
import { currentTheme, observeCurrentTheme } from '../../composables/useRandomData';
import {
createTreeColumns,
createTreeConfig,
createTreeFilterConfig,
createTreeRows,
TREE_COLUMN_TYPES,
TREE_DATA_GRID_CONTEXT_MENU,
TREE_DATA_GRID_FORMATTING,
TREE_EXPORT_CONFIG,
TREE_PLUGINS,
TREE_ROW_ORDER_CONFIG,
TREE_ROW_SELECT_CONFIG,
TREE_STICKY_CELLS_CONFIG,
type TreeDataRow,
} from './tree.shared';
import { mountTreeToolbar } from './tree.toolbar';
import './tree.scss';
defineCustomElements();
export function load(parentSelector: string, rows?: TreeDataRow[]) {
const parent = document.querySelector(parentSelector);
if (!parent) return () => undefined;
const source = rows?.length ? rows : createTreeRows();
let treeConfig = createTreeConfig(source);
let expandedRowIds = new Set(treeConfig.expandedRowIds);
const container = document.createElement('section');
container.className = 'tree-showcase';
container.setAttribute('aria-label', 'Tree Data organization explorer');
const toolbar = document.createElement('div');
const grid = document.createElement('revo-grid');
grid.className = 'tree-grid';
const initialDarkTheme = currentTheme().isDark();
grid.theme = initialDarkTheme ? 'darkMaterial' : 'material';
grid.plugins = TREE_PLUGINS;
grid.columns = createTreeColumns(source);
grid.columnTypes = TREE_COLUMN_TYPES;
grid.rowOrder = TREE_ROW_ORDER_CONFIG;
grid.rowSelect = TREE_ROW_SELECT_CONFIG;
grid.tree = treeConfig;
grid.range = true;
grid.readonly = true;
grid.stickyCells = TREE_STICKY_CELLS_CONFIG;
grid.resize = true;
grid.filter = createTreeFilterConfig(source);
grid.dataGridFormatting = TREE_DATA_GRID_FORMATTING;
grid.dataGridContextMenu = TREE_DATA_GRID_CONTEXT_MENU;
grid.stretch = true;
grid.hideAttribution = true;
const expandAll = () => grid.dispatchEvent(new CustomEvent(TREE_EXPAND_ALL_EVENT));
const collapseAll = () => grid.dispatchEvent(new CustomEvent(TREE_COLLAPSE_ALL_EVENT));
const toggleSticky = (checked: boolean) => {
treeConfig = createTreeConfig(source, {
expandedRowIds,
stickyParents: checked,
});
grid.tree = treeConfig;
grid.columns = createTreeColumns(source, checked);
};
const syncTreeState = (event: Event) => {
expandedRowIds = new Set(
(event as CustomEvent<{ expandedRowIds: Set<string> }>).detail.expandedRowIds,
);
};
const exportToExcel = async () => {
const plugins = await grid.getPlugins();
const exportPlugin = plugins.find((plugin) => plugin instanceof ExportExcelPlugin) as ExportExcelPlugin | undefined;
await exportPlugin?.export(TREE_EXPORT_CONFIG);
};
const unmountToolbar = mountTreeToolbar(toolbar, {
expandAll, collapseAll, exportToExcel, setStickyParents: toggleSticky,
});
grid.addEventListener(TREE_STATE_CHANGED_EVENT, syncTreeState);
container.append(toolbar, grid);
parent.appendChild(container);
grid.source = source;
const disconnectTheme = observeCurrentTheme((isDark) => {
grid.theme = isDark ? 'darkMaterial' : 'material';
});
return () => {
disconnectTheme();
unmountToolbar();
grid.removeEventListener(TREE_STATE_CHANGED_EVENT, syncTreeState);
container.remove();
};
}

RevoGrid has two different ways to show hierarchical rows, and they solve different problems:

  • Key grouping uses the grid’s built-in grouping configuration, for example grid.grouping = { props: ['country', 'city'] }. The grid reads one or more column values, creates synthetic group header rows for each matching key, and places source rows under those generated groups. Use it when the hierarchy should be calculated from repeated values such as category, region, status, or date.
  • TreeDataPlugin uses explicit row relationships from your data, normally id and parentId. The plugin keeps your original rows as the tree nodes, computes tree metadata such as level, expanded state, and visibility, and trims collapsed descendants from the viewport. Use it when the hierarchy already exists in the data, such as folders, tasks and subtasks, organization charts, bill of materials, or nested records.

In short, key grouping answers “which rows share the same values?”, while the tree plugin answers “which row is the parent of this row?”. Key grouping is value-driven and creates group rows; tree data is relationship-driven and renders your existing rows as parent and child nodes.

Key Features

  • Hierarchical Data Support: Automatically organizes flat data into a tree structure based on customizable id, parentId, and level fields. - Expandable Rows: Expand and collapse rows dynamically to reveal or hide child rows. - Customizable Templates: Supports tree-specific cell templates for better customization. - Root Parent Support: Define custom root parent identifiers for flexibility in tree structure.

To build the hierarchical tree structure, each data item must include the following fields:

  • id: A unique identifier for each row.
  • parentId: Links the item to its parent row. Root-level rows should use the rootParentId value (default: 'root').

Without these fields, the plugin cannot establish the necessary parent-child relationships for the tree structure.

const data = [
{ id: '1', parentId: 'root', name: 'Parent 1' },
{ id: '2', parentId: '1', name: 'Child 1.1' },
{ id: '3', parentId: '1', name: 'Child 1.2' },
{ id: '4', parentId: 'root', name: 'Parent 2' },
];

The plugin supports the following options for customization:

  • idField: Defines the field representing unique row identifiers. Default: ‘id’.
  • parentIdField: Specifies the field indicating parent row IDs. Default: ‘parentId’.
  • levelField: Sets the field to store hierarchy levels. Default: ‘level’.
  • rootParentId: Defines the identifier for root-level rows. Default: ‘root’.
  • expandedRowIds: A Set of row IDs to predefine expanded rows.
  • selectionFilterMode: Checkbox filters default to 'exclude-subtree', which hides complete unchecked branches. Use 'match-path' to keep ancestors of checked children and descendants of checked parents visible as context. Gantt enables 'match-path' for its task table.

You can provide these options via revogrid.additionalData?.tree to customize the plugin’s behavior:

grid.additionalData = {
tree: {
idField: 'customId',
parentIdField: 'customParentId',
levelField: 'depth',
rootParentId: null,
expandedRowIds: new Set(['row1', 'row2']), // Pre-expanded rows
},
};

By setting these options, you can adapt the plugin to different data structures and define default states for the tree.

Use expandRowsById() to reveal several branches in one tree update. It preserves existing expanded rows and skips updates when all supplied IDs are already expanded.

import { TreeDataPlugin } from '@revolist/revogrid-pro';
const tree = (await grid.getPlugins()).find(
(plugin) => plugin instanceof TreeDataPlugin,
);
tree?.expandRowsById(['phase-1', 'phase-2']);

Tree rows can animate while they are trimmed during collapse and restored during expand. Enable tree.animation; TreeDataPlugin registers DimensionAnimationPlugin automatically when it is not already present.

import { TreeDataPlugin } from '@revolist/revogrid-pro';
grid.plugins = [TreeDataPlugin];
grid.tree = {
animation: true,
};
grid.dimensionAnimation = {
duration: 180,
};

When tree.animation is not enabled, tree collapse and expand use the existing immediate trim behavior.

For paged roots and lazy children with server sorting and filtering, see Remote Tree Loading.