Lattice Grid

demo D67

The aggregations in React

sum, avg, min, max, count, countValues, first, last, one column each

total: 'sum'

This grid shows the built-in aggregations one per column: sum, average, min, max, count, count of values, first and last. It reduces a column, or a group, to the single figure someone asked for, so a footer answers the question without a separate calculation.

Building…
Loading a live grid…

In React, an aggregation is one key on the column definition: total set to 'sum', 'avg', 'min', 'max' or 'count', and 'countValues', 'first' or 'last' for text columns. The LatticeGrid component you build with createLatticeGrid takes the columns array and the grandTotalRow prop, so the figures sit in a row pinned under the viewport. The grid above groups twenty thousand service records by team, one reduction per column. The React code underneath is the same configuration, and the notes after it cover reading the totals back.

Install and import

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

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

The configuration

<link rel="stylesheet" href="https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.min.css">

<div id="grid"></div>

<script type="module">
  import React from 'https://esm.sh/react@18';
  import { createRoot } from 'https://esm.sh/react-dom@18/client';
  import { createGrid } from 'https://cdn.latticegrid.dev/lattice-grid@1.133.1/lattice-grid.esm.min.js';
  import createLatticeGrid from 'https://cdn.latticegrid.dev/lattice-grid@1.133.1/modules/react.esm.min.js';

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

  // One reduction per column, named on total: sum, avg, min, max and count for
  // numbers, and countValues, first and last for the rest. Each rolls up in the
  // grand total row and, with a grouped column, in every group's subtotal.
  const columns = [
    { field: 'team', title: 'Team', group: { enabled: true, index: 0 } },
    { field: 'service', title: 'Service', total: 'count' },
    { field: 'instances', title: 'sum', type: 'number', total: 'sum' },
    { field: 'p95Ms', title: 'avg', type: 'number', total: 'avg' },
    { field: 'p50Ms', title: 'min', type: 'number', total: 'min' },
    { field: 'p99Ms', title: 'max', type: 'number', total: 'max' },
    { field: 'owner', title: 'countValues', total: 'countValues' },
    { field: 'region', title: 'first', total: 'first' },
    { field: 'tier', title: 'last', total: 'last' },
  ];

  const rows = [/* 20,000 service records */];

  function App() {
    return (
      <LatticeGrid
        rowKey="id"
        grandTotalRow="bottom"
        columns={columns}
        rows={rows}
        style={{ height: '540px' }}
      />
    );
  }

  createRoot(document.getElementById('grid')).render(<App />);
</script>

API notes for aggregations in React

  • Declaring an aggregate. Put total on the column definition. The built-in names are sum, min, max, avg, count, first, last, countValues and median. The demo uses one of each of the first eight, one per column. countValues counts the non-blank values, and first and last take the value at the ends of the group in its current order. { fn: 'percentile', p: 0.9 } is accepted wherever a name is, and so is a function (values, ctx) => result for your own reduction.
  • Different figures for groups and the grand total. total applies to both. groupTotal overrides it for group subtotals and grandTotal overrides it for the grand total row only, so a column can average within each group while the grand total sums.
  • Turning on the grand total. Pass grandTotalRow as a prop on LatticeGrid. 'bottom', as in the demo, pins the row beneath the viewport so it stays in view while the rows scroll and is not counted by rows.count(). true makes it the last display row instead, and it is counted. Leave it out for no grand total row.
  • Turning on group footers. Group a column with group: { enabled: true, index: 0 }, as team is here, and every group row carries the reductions of the columns that have a total. Set the groupFooter prop as well for a totals line at the foot of each group.
  • Props. Every grid configuration key is a prop on LatticeGrid. When the reference of a prop changes the component applies it to the live grid with grid.setAll() and never rebuilds the grid. Give the grid a height, as the demo’s style={{ height: '540px' }} does.
  • Reading a total back. Take the grid from the ref after mount. A group row’s own reductions are in row.totals, keyed by column id, on the row from grid.rows.get(index) where row.group is true. With grandTotalRow set to true the grand total is the last display row, so grid.rows.get(grid.rows.count() - 1) reaches it. grid.columns.all() shows the reduction each column carries.
  • Changing an aggregate at run time. grid.columns.setTotal('instances', 'avg') changes a column, and { scope: 'group' } or { scope: 'grand' } as the third argument changes one scope only. grid.columns.aggregates('instances') lists the names meaningful for that column.
  • Callbacks. onGroupToggled receives group:toggled as a group opens or closes. onTotalsContextmenu receives totals:contextmenu, with the colId the menu was requested on, from the pinned totals row.

How do I read a group’s total from a React ref?

Hold the ref the adapter forwards, const ref = useRef(null), and pass it as ref={ref}. The ref exposes .grid once the component has mounted, and it is null before then, so read it in an event handler or an effect rather than during render. Then find the group row with ref.current.grid.rows.get(index) and read row.totals.instances.

Can the grand total sum while each group averages in React?

Yes. Declare { field: 'p95Ms', total: 'avg', grandTotal: 'sum' }, or the reverse with groupTotal. The override applies to its own scope only, and the column’s total still covers the other one.

Does the total update when my React state changes the rows?

Pass a new rows array and the component applies it to the grid already on screen with setAll(), so the grid is not rebuilt and the totals follow the new data. Hold the array in state or useMemo, not as a fresh literal in every render.

Summarising a column with sum, avg, min, max, count and more

An aggregation reduces every value in a column, or every value within a group, down to a single figure: a sum of “Revenue”, the average of “Response time”, the earliest “first” value or the latest “last” one. A developer reaches for it wherever a column of raw numbers needs a headline figure alongside it, whether that is a grand total row, a per-group subtotal, or a pivoted summary table. Lattice Grid assigns the function per column with total: 'sum', and the same setting accepts 'avg', 'min', 'max', 'count', 'countValues', 'first' or 'last', so a column of currency values and a column of timestamps can each carry the aggregation that actually suits their data rather than sharing one formula. Because this is a JavaScript data grid built around incremental state rather than repeated full-table scans, adding or removing a row updates the affected totals directly instead of walking every row again, which keeps aggregation cost proportional to the change rather than to the size of the dataset. Grouping, group footers and the grand total row all read from these same per-column definitions, so a sum defined once is reused everywhere a total for that column is displayed, with no separate calculation to keep in sync.

How do I calculate a sum or average for a column in a data grid?

Set total: 'sum' on the column definition, or 'avg', 'min', 'max', 'count', 'countValues', 'first', 'last' for the other built-in reducers. Lattice Grid applies the chosen function to the column’s values, and reuses that same definition for group footers, the grand total row and pivot summaries, so the aggregation only needs to be declared once per column.