Grouping

DataGrid grouping and aggregation

Basic grouping

Pass grouping with an array of column ids to useDataGrid to group rows by one or more columns. Each group is displayed as a group row with the grouped value and the number of rows in the group:

Department
First Name
Last Name
Salary
Status
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      { accessorKey: 'salary', header: 'Salary' },
      { accessorKey: 'status', header: 'Status' },
    ],
    withGrouping: true,
    grouping: ['department'],
  });

  return <DataGrid store={store} />;
}

Group rows

A group row displays its label in the cell of the grouping column, for example Department: Engineering (5). Columns with aggregationFn display their aggregatedCell. Click anywhere on a group row or press Enter / Space while it is focused to toggle the group. Set withTintedGroupRows on DataGrid to paint group rows with the striped color:

Department
First Name
Last Name
Salary
Status
Average
$81,389
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      {
        accessorKey: 'salary',
        header: 'Salary',
        meta: {
          align: 'end',
          formatAggregatedValue: (value) => `$${Math.round(Number(value)).toLocaleString()}`,
        },
        aggregationFn: 'mean',
        aggregatedCell: ({ getValue }) => `Avg $${Math.round(getValue<number>()).toLocaleString()}`,
      },
      { accessorKey: 'status', header: 'Status' },
    ],
    getRowId: (row) => row.id,
    withGrouping: true,
    withRowSelection: true,
    grouping: ['department'],
  });

  return <DataGrid store={store} withTintedGroupRows />;
}

Interactive grouping

Use controlled grouping state with onGroupingChange to change grouping dynamically. With withColumnMenu on DataGrid, every column that can be grouped gets Group by this column / Ungroup items in its header menu:

Active grouping: none

First Name
Last Name
Department
Salary
Status
AliceJohnsonEngineering95000active
BobSmithMarketing72000active
CarolWilliamsSales68000active
DavidBrownHR65000inactive
EvaDavisFinance88000active
FrankMillerEngineering102000active
GraceWilsonMarketing76000active
HenryTaylorSales71000inactive
IreneAndersonEngineering97000active
JamesThomasFinance91000active
KarenJacksonHR63000active
LeoWhiteEngineering110000active
MiaHarrisSales74000active
NathanMartinMarketing69000inactive
OliviaGarciaFinance85000active
PatrickMartinezEngineering99000active
QuinnRobinsonHR67000active
RachelClarkSales73000active
import { useState } from 'react';
import { GroupingState } from '@tanstack/react-table';
import { Button, Code, Group, Text } from '@mantine/core';
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const [grouping, setGrouping] = useState<GroupingState>([]);

  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      { accessorKey: 'salary', header: 'Salary' },
      { accessorKey: 'status', header: 'Status' },
    ],
    withGrouping: true,
    grouping,
    onGroupingChange: setGrouping,
  });

  const toggleGrouping = (columnId: string) => {
    setGrouping((prev) =>
      prev.includes(columnId) ? prev.filter((id) => id !== columnId) : [...prev, columnId]
    );
  };

  return (
    <div>
      <Text mb="xs">
        Active grouping: <Code>{grouping.length ? grouping.join(', ') : 'none'}</Code>
      </Text>
      <Group mb="md">
        <Button
          size="xs"
          variant={grouping.includes('department') ? 'filled' : 'default'}
          onClick={() => toggleGrouping('department')}
        >
          Group by Department
        </Button>
        <Button
          size="xs"
          variant={grouping.includes('status') ? 'filled' : 'default'}
          onClick={() => toggleGrouping('status')}
        >
          Group by Status
        </Button>
        <Button size="xs" variant="default" onClick={() => setGrouping([])}>
          Clear grouping
        </Button>
      </Group>
      <DataGrid store={store} />
    </div>
  );
}

Multi-level grouping

Pass multiple column ids in the grouping array to create nested groups. The first id is the outermost group:

Department
Status
First Name
Last Name
Salary
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      { accessorKey: 'salary', header: 'Salary' },
      { accessorKey: 'status', header: 'Status' },
    ],
    withGrouping: true,
    grouping: ['department', 'status'],
  });

  return <DataGrid store={store} />;
}

Aggregation

Add aggregationFn and aggregatedCell to column definitions to display computed values in group rows. TanStack Table provides built-in aggregation functions, for example sum, mean and count:

Grouping by: department

Department
First Name
Last Name
Salary
Count
Average
$81,389
Count
18
import { useState } from 'react';
import { GroupingState } from '@tanstack/react-table';
import { Button, Code, Group, Text } from '@mantine/core';
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const [grouping, setGrouping] = useState<GroupingState>(['department']);

  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      {
        accessorKey: 'salary',
        header: 'Salary',
        meta: {
          formatAggregatedValue: (value) => `$${Math.round(Number(value)).toLocaleString()}`,
        },
        aggregationFn: 'mean',
        aggregatedCell: ({ getValue }) =>
          `Avg: $${Math.round(getValue() as number).toLocaleString()}`,
      },
      {
        accessorKey: 'status',
        header: 'Count',
        aggregationFn: 'count',
        aggregatedCell: ({ getValue }) => `${getValue()} employees`,
      },
    ],
    withGrouping: true,
    grouping,
    onGroupingChange: setGrouping,
  });

  return (
    <div>
      <Text mb="xs">
        Grouping by: <Code>{grouping.length ? grouping.join(', ') : 'none'}</Code>
      </Text>
      <Group mb="md">
        <Button
          size="xs"
          variant={grouping.includes('department') ? 'filled' : 'default'}
          onClick={() =>
            setGrouping((prev) =>
              prev.includes('department')
                ? prev.filter((id) => id !== 'department')
                : [...prev, 'department']
            )
          }
        >
          Group by Department
        </Button>
        <Button
          size="xs"
          variant={grouping.includes('status') ? 'filled' : 'default'}
          onClick={() =>
            setGrouping((prev) =>
              prev.includes('status')
                ? prev.filter((id) => id !== 'status')
                : [...prev, 'status']
            )
          }
        >
          Group by Status
        </Button>
        <Button size="xs" variant="default" onClick={() => setGrouping([])}>
          Clear
        </Button>
      </Group>
      <DataGrid store={store} />
    </div>
  );
}

Totals row

Every column with aggregationFn also gets a cell in the totals row, which is rendered in the table footer whether or not the grid is grouped. Totals aggregate the filtered rows across all pages.

Built-in aggregations are labelled with the aggregation* labels (Sum, Average, etc.), custom functions have no label. Use meta.aggregationLabel to set the label and meta.formatAggregatedValue to format the value:

const columns = [
  {
    accessorKey: 'salary',
    header: 'Salary',
    aggregationFn: 'sum',
    meta: {
      align: 'end',
      aggregationLabel: 'Payroll',
      formatAggregatedValue: (value) => `$${Number(value).toLocaleString()}`,
    },
  },
];

Custom aggregation

Use constructAggregationFn from TanStack Table to define a custom aggregation function. It receives the rows and a getValue accessor:

import { constructAggregationFn } from '@tanstack/react-table';

const salaryTotal = constructAggregationFn({
  aggregate: ({ rows, getValue }) => {
    const values = rows.map((row) => getValue(row) as number);
    const total = values.reduce((sum, val) => sum + val, 0);
    return { total, count: values.length };
  },
});

const columns = [
  {
    accessorKey: 'salary',
    header: 'Salary',
    aggregationFn: salaryTotal,
    aggregatedCell: ({ getValue }) => {
      const { total, count } = getValue();
      return `$${total.toLocaleString()} (${count} employees)`;
    },
  },
];

groupedColumnMode

The groupedColumnMode option controls what happens to a column after it is used for grouping. With 'reorder', grouped columns cannot be reordered while they are grouped, see Column reorder.

ValueBehavior
'reorder' (default)Grouped columns are moved to the front, right after the utility columns
'remove'Grouped columns are hidden
falseGrouped columns stay in their original position

groupedColumnMode: remove

First Name
Last Name
Salary
Status
import { useState } from 'react';
import { Button, Group, Text } from '@mantine/core';
import { DataGrid, useDataGrid } from '@mantine/data-grid';
import { employees } from './data';

function Demo() {
  const [mode, setMode] = useState<'reorder' | 'remove' | false>('remove');

  const store = useDataGrid({
    data: employees,
    columns: [
      { accessorKey: 'firstName', header: 'First Name' },
      { accessorKey: 'lastName', header: 'Last Name' },
      { accessorKey: 'department', header: 'Department' },
      { accessorKey: 'salary', header: 'Salary' },
      { accessorKey: 'status', header: 'Status' },
    ],
    withGrouping: true,
    grouping: ['department'],
    groupedColumnMode: mode,
  });

  return (
    <div>
      <Text mb="xs">
        groupedColumnMode: <strong>{String(mode)}</strong>
      </Text>
      <Group mb="md">
        <Button
          size="xs"
          variant={mode === 'reorder' ? 'filled' : 'default'}
          onClick={() => setMode('reorder')}
        >
          reorder
        </Button>
        <Button
          size="xs"
          variant={mode === 'remove' ? 'filled' : 'default'}
          onClick={() => setMode('remove')}
        >
          remove
        </Button>
        <Button
          size="xs"
          variant={mode === false ? 'filled' : 'default'}
          onClick={() => setMode(false)}
        >
          false
        </Button>
      </Group>
      <DataGrid store={store} />
    </div>
  );
}

Group selection

With withRowSelection, the checkbox of a group row selects or deselects all rows of the group. Group rows themselves are never selected, rowSelection contains data row ids only. The group checkbox is not displayed in single selection mode.

Expand and collapse all groups

Use store.table.toggleAllRowsExpanded() to expand or collapse every group at once. store.table.getIsAllRowsExpanded() returns the current state:

function Demo() {
  const store = useDataGrid({ data, columns, withGrouping: true, grouping: ['department'] });

  return (
    <div>
      <Button onClick={() => store.table.toggleAllRowsExpanded()}>
        {store.table.getIsAllRowsExpanded() ? 'Collapse all' : 'Expand all'}
      </Button>
      <DataGrid store={store} />
    </div>
  );
}

Controlled grouping

Pass grouping and onGroupingChange to useDataGrid for controlled grouping state. The state is an array of column ids, the first id is the outermost group:

import { useState } from 'react';
import { GroupingState } from '@tanstack/react-table';
import { DataGrid, useDataGrid } from '@mantine/data-grid';

function Demo() {
  const [grouping, setGrouping] = useState<GroupingState>(['department']);

  const store = useDataGrid({
    data,
    columns,
    grouping,
    onGroupingChange: setGrouping,
  });

  return <DataGrid store={store} />;
}

Cell selection

With withCellSelection, group cells are excluded from ranges. The label cell of a group row is the keyboard target, Enter / Space toggle the group.