Lattice Grid Buy a licence

react data grid · tree data

React Grid: Tree Data

A hierarchy needs one thing from your data: each row naming its own parent. The grid builds the expander column, the indent and the totals from that reference, so you configure a tree the same way you configure any other column.

Also in: Angular

Install and import

npm install @toclocoinc/lattice-grid
# free on localhost; a production domain needs a licence key (see /pricing/)

The files

lattice.ts

// lattice.ts
import React from 'react';
import { createGrid } from '@toclocoinc/lattice-grid';
import '@toclocoinc/lattice-grid/css';
import { createLatticeGrid } from '@toclocoinc/lattice-grid/modules/react';

export const LatticeGrid = createLatticeGrid({ React, createGrid });

Estate.tsx

// Estate.tsx
import React from 'react';
import { createRoot } from 'react-dom/client';
import { LatticeGrid } from './lattice';

// Every node is a real row naming its own parent. The grid generates the
// tree column itself: the expander, the indent and the shown name all come
// from "label", so "name" is deliberately not declared as a column below.
const tree = { parentKey: 'parentId', label: 'name', title: 'Estate' };

const columns = [
  { field: 'kind', title: 'Level', filter: { type: 'set' }, layout: { width: 120 } },
  {
    field: 'status', title: 'Status', filter: { type: 'set' }, layout: { width: 140 },
    cell: { decoration: 'pill', variant: { map: { live: 'success', provisioning: 'info', ceased: 'neutral' } } },
  },
  { field: 'devices', title: 'Devices', type: 'number', total: 'sum', layout: { width: 120 } },
  { field: 'charge', title: 'Monthly charge', type: 'number',
    format: { style: 'currency', currency: 'GBP', decimals: 0 }, total: 'sum', layout: { width: 180 } },
];

const rows = [/* estate nodes, each naming its parent */];

function Estate() {
  return (
    <LatticeGrid
      rowKey="id"
      selection="multiple"
      grandTotalRow="bottom"
      tree={tree}
      toolPanel={{ side: 'left', panels: ['columns', 'filters', 'views', 'quick'],
        actions: ['undo', 'redo', 'export', 'restore', 'maximise'], exportName: 'lattice-demo' }}
      columns={columns}
      rows={rows}
      style={{ height: '480px' }}
    />
  );
}

createRoot(document.getElementById('estate')!).render(<Estate />);

See it running

Building…
Loading a live grid…

Open this demo's React tab →

Working in React

The label field is not a column. tree.label names the field the tree column shows; declaring that same field again in columns would draw it twice, so leave it out of the array and let the tree configuration own it.

Totals roll up the hierarchy. grandTotalRow and a column's own total both read the whole tree, not just the rows a reader has expanded, so a collapsed branch still contributes to the figure above it.

Expand and collapse state is grid state, held by the instance rather than by React, so it survives a parent re-render the same way group state does.

Related