Aggregation and Grouping Feature Guide
Material React Table has built-in grouping and aggregation features. There are options for both automatic client-side grouping and aggregation, as well as manual server-side grouping and aggregation. This guide will walk you through the different options and how to use and customize them.
Relevant Table Options
# | Prop Name | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
| TanStack Table Grouping Docs | |||
2 |
|
| MRT Expanding Sub Rows Docs | ||
3 |
| MRT Aggregation and Grouping Docs | |||
4 |
| ||||
5 |
| TanStack Table Grouping Docs | |||
6 |
|
| TanStack Table Grouping Docs | ||
7 |
| TanStack Table Grouping Docs | |||
8 |
| Material UI Chip Props | |||
9 |
| TanStack Table Grouping Docs | |||
10 |
| ||||
Relevant Column Options
# | Column Option | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
| ||||
2 |
| MRT Data Columns Docs | |||
3 |
| ||||
4 |
| ||||
Relevant State
# | State Option | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
|
| TanStack Table Expanding Docs | ||
2 |
|
| TanStack Table Grouping Docs | ||
Enable Grouping
To enable grouping, set the enableGrouping
table option to true
. This will both add a drag handle button so that columns can be dragged to the dropzone to be grouped and will add an entry column actions menu to group or ungroup a column.
const table = useMaterialReactTable({columns,data,enableGrouping: true,});
Disable Grouping Per Column
const columns = [{accessorKey: 'name',header: 'Name',enableGrouping: false, // disable grouping for this column},{accessorKey: 'age',header: 'Age',},];const table = useMaterialReactTable({columns,data,enableGrouping: true,});return <MaterialReactTable table={table} />;
Hide Drag Buttons for Grouping
If you do not want the drag buttons that come with the grouping feature, you can independently disable them without disabling the grouping feature entirely by setting the enableColumnDragging
table option to false
.
const table = useMaterialReactTable({columns,data,enableGrouping: true,enableColumnDragging: false, //do not show drag handle buttons, but still show grouping options in column actions menu});return <MaterialReactTable table={table} />;
Group Columns by Default
If you want columns to be grouped by default, you can set the grouping
state in either the initialState
or state
table option.
const table = useMaterialReactTable({columns,data,enableGrouping: true,initialState: { grouping: ['location', 'department'] }, //group by location and department by default});return <MaterialReactTable table={table} />;
Expand Grouped Rows by Default
In addition to grouping columns by default, you may also want those grouped rows to be expanded and visible by default, too. You can do this by setting the expanded
state to true
in either the initialState
or state
table option.
const table = useMaterialReactTable({columns,data,enableGrouping: true,initialState: {grouping: ['location', 'department'], //group by location and department by default and expand grouped rowsexpanded: true, //show grouped rows by default},});return <MaterialReactTable table={table} />;
Aggregation on Grouped Rows
One of the cool features of Material React Table is that it can automatically aggregate the data in grouped rows. To enable this, you must specify both an aggregationFn
and an AggregatedCell
render option on a column definition.
Built-in Aggregation Functions
There are several built-in aggregation functions available that you can use. They are:
count
- Finds the number of rows in a groupextent
- Finds the minimum and maximum values of a group of rowsmax
- Finds the maximum value of a group of rowsmean
- Finds the average value of a group of rowsmedian
- Finds the median value of a group of rowsmin
- Finds the minimum value of a group of rowssum
- sums the values of a group of rowsuniqueCount
- Finds the number of unique values of a group of rowsunique
- Finds the unique values of a group of rows
All of these built-in aggregation functions are from TanStack Table
const columns = [{accessorKey: 'team', //grouped by team in initial state belowheader: 'Team',},{accessorKey: 'player',header: 'Player',},{accessorKey: 'points',header: 'Points',aggregationFn: 'sum', //calc total points for each team by adding up all the points for each player on the teamAggregatedCell: ({ cell }) => <div>Team Score: {cell.getValue()}</div>,},];const table = useMaterialReactTable({columns,data,enableGrouping: true,initialState: { grouping: ['team'], expanded: true },});return <MaterialReactTable table={table} />;
Custom Aggregation Functions
If none of these pre-built aggregation functions work for you, you can also pass in a custom aggregation function. The aggregation function will be passed in an array of values from the column that you are aggregating. It should return a single value that will be displayed in the aggregated cell.
If you are specifying a custom aggregation function, it must implement the following type:
export type AggregationFn<TData extends AnyData> = (getLeafRows: () => Row<TData>[],getChildRows: () => Row<TData>[]) => any
Aggregation on All Rows in Footer
Material React Table does not automatically aggregate all rows for you to calculate totals for the entire table. However, it is still easy enough to do this manually and add in your custom calculations into the footer
or Footer
of a column definition. It is recommended that you do any necessary aggregation calculations on your data in a useMemo hook before passing it to the columns footer in your columns definition.
//calculate the total points for all players in the table in a useMemo hookconst averageScore = useMemo(() => {const totalPoints = data.reduce((acc, row) => acc + row.points, 0);const totalPlayers = data.length;return totalPoints / totalPlayers;}, [data]);const columns = useMemo(() => [{accessorKey: 'name',header: 'Name',},{accessorKey: 'score',header: 'Score',Footer: () => <div>Average Score: {averageScore}</div>, //do not do calculations in render, do them in useMemo hook and pass them in here},],[averageScore],);
Please remember to perform heavy aggregation calculations in a useMemo hook to avoid unnecessary re-renders!
Custom Cell Renders for Aggregation and Grouping
There are a few custom cell render overrides that you should be aware of when using grouping and aggregation features.
AggregatedCell Column Option
"Aggregation Cells" are cells in an aggregated row (not a normal data row) that can display aggregates (avg, sum, etc.) of the data in a group. The cell that the table is grouped on, however, is not an Aggregate Cell, but rather a GroupedCell.
You can specify the custom render for these cells with the AggregatedCell
render option on a column definition.
const columns = [{accessorKey: 'points',header: 'Points',aggregationFn: 'sum',AggregatedCell: ({ cell }) => <div>Total Score: {cell.getValue()}</div>,},];
GroupedCell Column Option
"Grouped Cells" are cells in a grouped row (not a normal data row) that by default display the value that the rows are grouped on and the number of rows in the group. You can override the default render for these cells with the GroupedCell
render option on a column definition.
const columns = [{accessorKey: 'team',header: 'Team',GroupedCell: ({ cell }) => <div>Team: {cell.getValue()}</div>,},];
PlaceholderCell Column Option
"Placeholder Cells" are cells that are usually meant to be empty in grouped rows and columns. They are simply rendered with a value of null
by default, but you can override the default render for these cells with the PlaceholderCell
render option on a column definition.
const columns = [{accessorKey: 'team',header: 'Team',PlaceholderCell: ({ cell, row }) => (<div>{row.original.someOtherRowValue}</div>),},];
Aggregation/Grouping Example
State | First Name | Last Name | Age | Gender | Salary | ||
---|---|---|---|---|---|---|---|
Alabama(7) | Oldest by State: 64 | Average by State: $43,375 | |||||
Thad | Wiegand | 64 | Female | $56,146 | |||
Alivia | Ledner | 56 | Male | $12,591 | |||
Danyka | Gleason | 36 | Male | $71,238 | |||
Lionel | Hartmann | 30 | Nonbinary | $58,743 | |||
Reinhold | Reichel | 30 | Female | $30,531 | |||
Lurline | Koepp | 59 | Female | $10,645 | |||
Kody | Braun | 38 | Female | $63,733 | |||
Alaska(8) | Oldest by State: 59 | Average by State: $68,901 | |||||
Eloisa | Kohler | 31 | Male | $45,801 | |||
Kian | Hand | 56 | Male | $81,062 | |||
Loyce | Schmidt | 29 | Female | $76,295 | |||
Michale | Collier | 59 | Male | $75,197 | |||
Eldridge | Stroman | 42 | Male | $59,594 | |||
Alvera | Balistreri | 25 | Female | $79,844 | |||
Kayden | Emard | 35 | Female | $98,252 | |||
Domingo | Bauch | 36 | Female | $35,159 | |||
Arizona(1) | Oldest by State: 22 | Average by State: $54,027 | |||||
Gunner | Rolfson | 22 | Male | $54,027 | |||
Arkansas(4) | Oldest by State: 52 | Average by State: $58,194 | |||||
Max Age: 65 | Average Salary: $56,319 |
1import { useMemo } from 'react';2import { Box, Stack } from '@mui/material';3import {4 MaterialReactTable,5 useMaterialReactTable,6 type MRT_ColumnDef,7} from 'material-react-table';8import { data, type Person } from './makeData';910const Example = () => {11 const averageSalary = useMemo(12 () => data.reduce((acc, curr) => acc + curr.salary, 0) / data.length,13 [],14 );1516 const maxAge = useMemo(17 () => data.reduce((acc, curr) => Math.max(acc, curr.age), 0),18 [],19 );2021 const columns = useMemo<MRT_ColumnDef<Person>[]>(22 () => [23 {24 header: 'First Name',25 accessorKey: 'firstName',26 enableGrouping: false, //do not let this column be grouped27 },28 {29 header: 'Last Name',30 accessorKey: 'lastName',31 },32 {33 header: 'Age',34 accessorKey: 'age',35 aggregationFn: 'max', //show the max age in the group (lots of pre-built aggregationFns to choose from)36 //required to render an aggregated cell37 AggregatedCell: ({ cell, table }) => (38 <>39 Oldest by{' '}40 {table.getColumn(cell.row.groupingColumnId ?? '').columnDef.header}:{' '}41 <Box42 sx={{ color: 'info.main', display: 'inline', fontWeight: 'bold' }}43 >44 {cell.getValue<number>()}45 </Box>46 </>47 ),48 Footer: () => (49 <Stack>50 Max Age:51 <Box color="warning.main">{Math.round(maxAge)}</Box>52 </Stack>53 ),54 },55 {56 header: 'Gender',57 accessorKey: 'gender',58 //optionally, customize the cell render when this column is grouped. Make the text blue and pluralize the word59 GroupedCell: ({ cell, row }) => (60 <Box sx={{ color: 'primary.main' }}>61 <strong>{cell.getValue<string>()}s </strong> ({row.subRows?.length})62 </Box>63 ),64 },65 {66 header: 'State',67 accessorKey: 'state',68 },69 {70 header: 'Salary',71 accessorKey: 'salary',72 aggregationFn: 'mean',73 //required to render an aggregated cell, show the average salary in the group74 AggregatedCell: ({ cell, table }) => (75 <>76 Average by{' '}77 {table.getColumn(cell.row.groupingColumnId ?? '').columnDef.header}:{' '}78 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>79 {cell.getValue<number>()?.toLocaleString?.('en-US', {80 style: 'currency',81 currency: 'USD',82 minimumFractionDigits: 0,83 maximumFractionDigits: 0,84 })}85 </Box>86 </>87 ),88 //customize normal cell render on normal non-aggregated rows89 Cell: ({ cell }) => (90 <>91 {cell.getValue<number>()?.toLocaleString?.('en-US', {92 style: 'currency',93 currency: 'USD',94 minimumFractionDigits: 0,95 maximumFractionDigits: 0,96 })}97 </>98 ),99 Footer: () => (100 <Stack>101 Average Salary:102 <Box color="warning.main">103 {averageSalary?.toLocaleString?.('en-US', {104 style: 'currency',105 currency: 'USD',106 minimumFractionDigits: 0,107 maximumFractionDigits: 0,108 })}109 </Box>110 </Stack>111 ),112 },113 ],114 [averageSalary, maxAge],115 );116117 const table = useMaterialReactTable({118 columns,119 data,120 enableColumnResizing: true,121 enableGrouping: true,122 enableStickyHeader: true,123 enableStickyFooter: true,124 initialState: {125 density: 'compact',126 expanded: true, //expand all groups by default127 grouping: ['state'], //an array of columns to group by by default (can be multiple)128 pagination: { pageIndex: 0, pageSize: 20 },129 sorting: [{ id: 'state', desc: false }], //sort by state by default130 },131 muiToolbarAlertBannerChipProps: { color: 'primary' },132 muiTableContainerProps: { sx: { maxHeight: 700 } },133 });134135 return <MaterialReactTable table={table} />;136};137138export default Example;139
Multiple Aggregations Per column
You may want to calculate more than one aggregation per column. This is now easier if you are upgraded to at least v1.3.0. You can now specify an array of aggregationFn
s, and then reference the aggregation results from an array in the AggregatedCell
render option.
const columns = [{header: 'Salary',accessorKey: 'salary',aggregationFn: ['count', 'mean'], //multiple aggregation functionsAggregatedCell: ({ cell, table }) => (<div>{/*get the count from the first aggregation*/}<div>Count: {cell.getValue()[0]}</div>{/*get the average from the second aggregation*/}<div>Average Salary: {cell.getValue()[1]}</div></div>),},];
State | First Name | Last Name | Gender | Salary | |
---|---|---|---|---|---|
Alabama(7) | Count: 7 Average: $43,375 Median: $56,146 Min: $10,645 Max: $71,238 | ||||
Thad | Wiegand | Female | $56,146 | ||
Alivia | Ledner | Male | $12,591 | ||
Danyka | Gleason | Male | $71,238 | ||
Lionel | Hartmann | Nonbinary | $58,743 | ||
Reinhold | Reichel | Female | $30,531 | ||
Lurline | Koepp | Female | $10,645 | ||
Kody | Braun | Female | $63,733 | ||
Alaska(8) | Count: 8 Average: $68,901 Median: $75,746 Min: $35,159 Max: $98,252 | ||||
Eloisa | Kohler | Male | $45,801 | ||
Kian | Hand | Male | $81,062 | ||
Loyce | Schmidt | Female | $76,295 | ||
Michale | Collier | Male | $75,197 | ||
Eldridge | Stroman | Male | $59,594 | ||
Alvera | Balistreri | Female | $79,844 | ||
Kayden | Emard | Female | $98,252 | ||
Domingo | Bauch | Female | $35,159 | ||
Arizona(1) | Count: 1 Average: $54,027 Median: $54,027 Min: $54,027 Max: $54,027 | ||||
Gunner | Rolfson | Male | $54,027 | ||
Arkansas(4) | Count: 4 Average: $58,194 Median: $51,948 Min: $42,997 Max: $85,883 |
1import { useMemo } from 'react';2import { Box } from '@mui/material';3import {4 MaterialReactTable,5 useMaterialReactTable,6 type MRT_ColumnDef,7} from 'material-react-table';8import { data, type Person } from './makeData';910const localeStringOptions = {11 style: 'currency',12 currency: 'USD',13 minimumFractionDigits: 0,14 maximumFractionDigits: 0,15};1617const Example = () => {18 const columns = useMemo<MRT_ColumnDef<Person>[]>(19 () => [20 {21 header: 'First Name',22 accessorKey: 'firstName',23 },24 {25 header: 'Last Name',26 accessorKey: 'lastName',27 },28 {29 header: 'Gender',30 accessorKey: 'gender',31 },32 {33 header: 'State',34 accessorKey: 'state',35 },36 {37 header: 'Salary',38 accessorKey: 'salary',39 aggregationFn: ['count', 'mean', 'median', 'min', 'max'],40 //required to render an aggregated cell, show the average salary in the group41 AggregatedCell: ({ cell }) => (42 <>43 Count:{' '}44 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>45 {cell.getValue<Array<number>>()?.[0]}46 </Box>47 Average:{' '}48 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>49 {cell50 .getValue<Array<number>>()?.[1]51 ?.toLocaleString?.('en-US', localeStringOptions)}52 </Box>53 Median:{' '}54 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>55 {cell56 .getValue<Array<number>>()?.[2]57 ?.toLocaleString?.('en-US', localeStringOptions)}58 </Box>59 Min:{' '}60 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>61 {cell62 .getValue<Array<number>>()?.[3]63 ?.toLocaleString?.('en-US', localeStringOptions)}64 </Box>65 Max:{' '}66 <Box sx={{ color: 'success.main', fontWeight: 'bold' }}>67 {cell68 .getValue<Array<number>>()?.[4]69 ?.toLocaleString?.('en-US', localeStringOptions)}70 </Box>71 </>72 ),73 //customize normal cell render on normal non-aggregated rows74 Cell: ({ cell }) => (75 <>76 {cell77 .getValue<number>()78 ?.toLocaleString?.('en-US', localeStringOptions)}79 </>80 ),81 },82 ],83 [],84 );8586 const table = useMaterialReactTable({87 columns,88 data,89 enableGrouping: true,90 enableStickyHeader: true,91 initialState: {92 density: 'compact',93 expanded: true, //expand all groups by default94 grouping: ['state'], //an array of columns to group by by default (can be multiple)95 pagination: { pageIndex: 0, pageSize: 20 },96 sorting: [{ id: 'state', desc: false }], //sort by state by default97 },98 muiToolbarAlertBannerChipProps: { color: 'primary' },99 muiTableContainerProps: { sx: { maxHeight: 700 } },100 });101102 return <MaterialReactTable table={table} />;103};104105export default Example;106
Manual Grouping
Manual Grouping means that the data
that you pass to the table is already grouped and aggregated, and you do not want Material React Table to do any of the grouping or aggregation for you. This is useful if you are using a backend API to do the grouping and aggregation for you, and you just want to display the results. However, you will need to put your data in the specific format that the expanding
features understand.