MRT logoMantine React Table

On This Page

    Aggregation and Grouping Feature Guide

    Mantine 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
    1Record<string, AggregationFn>TanStack Table Grouping Docs
    2booleantrueMRT Expanding Sub Rows Docs
    3booleanMRT Aggregation and Grouping Docs
    4boolean
    5(table: Table<TData>) => () => RowModel<TData>TanStack Table Grouping Docs
    6false | 'reorder' | 'remove'reorderTanStack Table Grouping Docs
    7BadgeProps| ({ table }} => BadgePropsMantine Chip Docs
    8booleanTanStack Table Grouping Docs
    9OnChangeFn<GroupingState>TanStack Table Grouping Docs
    10'bottom' | 'top' | 'head-overlay' | 'none'

    Relevant Column Options

    #
    Column Option
    Type
    Default Value
    More Info Links
    1({ cell, column, row, table }) => ReactNode
    2ReactNode | ({ column, footer, table }) => ReactNodeMRT Data Columns Docs
    3({ cell, column, row, table }) => ReactNode
    4boolean

    Relevant State

    #
    State Option
    Type
    Default Value
    More Info Links
    1Record<string, boolean> | boolean{}TanStack Table Expanding Docs
    2Array<string>[]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 = useMantineReactTable({
      columns,
      data,
      enableGrouping: true, //enable grouping
    });

    Disable Grouping Per Column

    const columns = [
      {
        accessorKey: 'name',
        header: 'Name',
        enableGrouping: false, // disable grouping for this column
      },
      {
        accessorKey: 'age',
        header: 'Age',
      },
    ];
    
    const table = useMantineReactTable({
      columns,
      data,
      enableGrouping: true, //enable grouping
    });
    
    return <MantineReactTable 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 = useMantineReactTable({
      columns,
      data,
      enableGrouping: true,
      enableColumnDragging: false, //do not show drag handle buttons, but still show grouping options in column actions menu
    });

    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 options.

    const table = useMantineReactTable({
      columns,
      data,
      enableGrouping: true,
      initialState: { grouping: ['location', 'department'] }, //group by location and department by default
    });

    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 options.

    const table = useMantineReactTable({
      columns,
      data,
      enableGrouping: true,
      initialState: {
        grouping: ['location', 'department'], //group by location and department by default and expand grouped rows
        expanded: true, //show grouped rows by default
      },
    });

    Aggregation on Grouped Rows

    One of the cool features of Mantine 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 group

    • extent - Finds the minimum and maximum values of a group of rows

    • max - Finds the maximum value of a group of rows

    • mean - Finds the average value of a group of rows

    • median - Finds the median value of a group of rows

    • min - Finds the minimum value of a group of rows

    • sum - sums the values of a group of rows

    • uniqueCount - Finds the number of unique values of a group of rows

    • unique - 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 below
        header: '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 team
        AggregatedCell: ({ cell }) => <div>Team Score: {cell.getValue()}</div>,
      },
    ];
    
    const table = useMantineReactTable({
      columns,
      data,
      enableGrouping: true,
      initialState: { grouping: ['team'], expanded: true },
    });
    
    return <MantineReactTable 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

    Mantine 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 hook
    const averageScore = useMemo(() => {
      const totalPoints = data.reduce((acc, row) => acc + row.points, 0);
      const totalPlayers = data.length;
      return totalPoints / totalPlayers;
    }, [data]);
    
    const columns = [
      {
        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
      },
    ];

    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 (2)Oldest by State:
    42
    Average by State:
    $71,105
    CelineJohnston42Non-binary$96,445
    HarmonBode14Female$45,764
    Alaska (7)Oldest by State:
    79
    Average by State:
    $61,315
    JulietUpton13Male$43,447
    MartinaMiller79Male$59,714
    HerbertLebsack33Female$68,645
    VivianRempel30Female$89,537
    RickWill36Female$48,064
    GuiseppeHeller31Female$20,924
    BenDooley34Non-binary$98,876
    Arizona (8)Oldest by State:
    77
    Average by State:
    $66,775
    SamanthaDibbert48Male$31,884
    JevonWuckert52Male$88,064
    LiaLowe77Male$56,479
    AbagailLuettgen25Male$99,154
    AlanisKuhic5Male$93,668
    ArvidAuer8Male$59,826
    RosellaBlanda54Female$76,754
    NathenWaelchi55Female$28,373
    Max Age:
    80
    Average Salary:
    $57,062

    Rows per page

    1-20 of 298

    import '@mantine/core/styles.css';
    import '@mantine/dates/styles.css'; //if using mantine date picker features
    import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
    import { useMemo } from 'react';
    import { Box, Stack } from '@mantine/core';
    import {
      MantineReactTable,
      useMantineReactTable,
      type MRT_ColumnDef,
    } from 'mantine-react-table';
    import { data, type Person } from './makeData';
    
    const Example = () => {
      const averageSalary = useMemo(
        () => data.reduce((acc, curr) => acc + curr.salary, 0) / data.length,
        [],
      );
    
      const maxAge = useMemo(
        () => data.reduce((acc, curr) => Math.max(acc, curr.age), 0),
        [],
      );
    
      const columns = useMemo<MRT_ColumnDef<Person>[]>(
        () => [
          {
            header: 'First Name',
            accessorKey: 'firstName',
            enableGrouping: false, //do not let this column be grouped
          },
          {
            header: 'Last Name',
            accessorKey: 'lastName',
          },
          {
            header: 'Age',
            accessorKey: 'age',
            aggregationFn: 'max', //show the max age in the group (lots of pre-built aggregationFns to choose from)
            //required to render an aggregated cell
            AggregatedCell: ({ cell, table }) => (
              <>
                Oldest by{' '}
                {table.getColumn(cell.row.groupingColumnId ?? '').columnDef.header}:{' '}
                <Box
                  style={{
                    color: 'skyblue',
                    display: 'inline',
                    fontWeight: 'bold',
                  }}
                >
                  {cell.getValue<number>()}
                </Box>
              </>
            ),
            Footer: () => (
              <Stack>
                Max Age:
                <Box color="orange">{Math.round(maxAge)}</Box>
              </Stack>
            ),
          },
          {
            header: 'Gender',
            accessorKey: 'gender',
            //optionally, customize the cell render when this column is grouped. Make the text blue and pluralize the word
            GroupedCell: ({ cell, row }) => (
              <Box style={{ color: 'skyblue' }}>
                <strong>{cell.getValue<string>()}s </strong> ({row.subRows?.length})
              </Box>
            ),
          },
          {
            header: 'State',
            accessorKey: 'state',
          },
          {
            header: 'Salary',
            accessorKey: 'salary',
            aggregationFn: 'mean',
            //required to render an aggregated cell, show the average salary in the group
            AggregatedCell: ({ cell, table }) => (
              <>
                Average by{' '}
                {table.getColumn(cell.row.groupingColumnId ?? '').columnDef.header}:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell.getValue<number>()?.toLocaleString?.('en-US', {
                    style: 'currency',
                    currency: 'USD',
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0,
                  })}
                </Box>
              </>
            ),
            //customize normal cell render on normal non-aggregated rows
            Cell: ({ cell }) => (
              <>
                {cell.getValue<number>()?.toLocaleString?.('en-US', {
                  style: 'currency',
                  currency: 'USD',
                  minimumFractionDigits: 0,
                  maximumFractionDigits: 0,
                })}
              </>
            ),
            Footer: () => (
              <Stack>
                Average Salary:
                <Box color="orange">
                  {averageSalary?.toLocaleString?.('en-US', {
                    style: 'currency',
                    currency: 'USD',
                    minimumFractionDigits: 0,
                    maximumFractionDigits: 0,
                  })}
                </Box>
              </Stack>
            ),
          },
        ],
        [averageSalary, maxAge],
      );
    
      const table = useMantineReactTable({
        columns,
        data,
        enableColumnResizing: true,
        enableGrouping: true,
        enableStickyHeader: true,
        enableStickyFooter: true,
        initialState: {
          density: 'xs',
          expanded: true,
          grouping: ['state'],
          pagination: { pageIndex: 0, pageSize: 20 },
          sorting: [{ id: 'state', desc: false }],
        },
        mantineToolbarAlertBannerBadgeProps: { color: 'blue', variant: 'outline' },
        mantineTableContainerProps: { style: { maxHeight: 700 } },
      });
    
      return <MantineReactTable table={table} />;
    };
    
    export default Example;

    Multiple Aggregations Per column

    You may want to calculate more than one aggregation per column. If so, you can specify an array of aggregationFns, 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 functions
        AggregatedCell: ({ 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
    Gender
    First Name
    Last Name
    Salary
    Alabama (3)Count:
    7
    Average:
    $43,375
    Median:
    $56,146
    Min:
    $10,645
    Max:
    $71,238
    Female (4)Count:
    4
    Average:
    $40,264
    Median:
    $43,339
    Min:
    $10,645
    Max:
    $63,733
    ThadWiegand$56,146
    ReinholdReichel$30,531
    LurlineKoepp$10,645
    KodyBraun$63,733
    Male (2)Count:
    2
    Average:
    $41,915
    Median:
    $41,915
    Min:
    $12,591
    Max:
    $71,238
    AliviaLedner$12,591
    DanykaGleason$71,238
    Nonbinary (1)Count:
    1
    Average:
    $58,743
    Median:
    $58,743
    Min:
    $58,743
    Max:
    $58,743
    LionelHartmann$58,743
    Alaska (2)Count:
    8
    Average:
    $68,901
    Median:
    $75,746
    Min:
    $35,159
    Max:
    $98,252
    Male (4)Count:
    4
    Average:
    $65,414
    Median:
    $67,396
    Min:
    $45,801
    Max:
    $81,062
    EloisaKohler$45,801
    KianHand$81,062
    MichaleCollier$75,197
    EldridgeStroman$59,594
    Female (4)Count:
    4
    Average:
    $72,388
    Median:
    $78,070
    Min:
    $35,159
    Max:
    $98,252
    LoyceSchmidt$76,295
    AlveraBalistreri$79,844

    Rows per page

    1-20 of 342

    import '@mantine/core/styles.css';
    import '@mantine/dates/styles.css'; //if using mantine date picker features
    import 'mantine-react-table/styles.css'; //make sure MRT styles were imported in your app root (once)
    import { useMemo } from 'react';
    import { Box } from '@mantine/core';
    import { MantineReactTable, type MRT_ColumnDef } from 'mantine-react-table';
    import { data, type Person } from './makeData';
    
    const localeStringOptions = {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    };
    
    const Example = () => {
      const columns = useMemo<MRT_ColumnDef<Person>[]>(
        () => [
          {
            header: 'First Name',
            accessorKey: 'firstName',
          },
          {
            header: 'Last Name',
            accessorKey: 'lastName',
          },
          {
            header: 'Gender',
            accessorKey: 'gender',
          },
          {
            header: 'State',
            accessorKey: 'state',
          },
          {
            header: 'Salary',
            accessorKey: 'salary',
            aggregationFn: ['count', 'mean', 'median', 'min', 'max'],
            //required to render an aggregated cell, show the average salary in the group
            AggregatedCell: ({ cell }) => (
              <>
                Count:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell.getValue<Array<number>>()?.[0]}
                </Box>
                Average:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell
                    .getValue<Array<number>>()?.[1]
                    ?.toLocaleString?.('en-US', localeStringOptions)}
                </Box>
                Median:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell
                    .getValue<Array<number>>()?.[2]
                    ?.toLocaleString?.('en-US', localeStringOptions)}
                </Box>
                Min:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell
                    .getValue<Array<number>>()?.[3]
                    ?.toLocaleString?.('en-US', localeStringOptions)}
                </Box>
                Max:{' '}
                <Box style={{ color: 'green', fontWeight: 'bold' }}>
                  {cell
                    .getValue<Array<number>>()?.[4]
                    ?.toLocaleString?.('en-US', localeStringOptions)}
                </Box>
              </>
            ),
            //customize normal cell render on normal non-aggregated rows
            Cell: ({ cell }) => (
              <>
                {cell
                  .getValue<number>()
                  ?.toLocaleString?.('en-US', localeStringOptions)}
              </>
            ),
          },
        ],
        [],
      );
    
      return (
        <MantineReactTable
          columns={columns}
          data={data}
          enableGrouping
          enableStickyHeader
          initialState={{
            density: 'xs',
            expanded: true, //expand all groups by default
            grouping: ['state', 'gender'], //an array of columns to group by by default (can be multiple)
            pagination: { pageIndex: 0, pageSize: 20 },
            sorting: [{ id: 'state', desc: false }], //sort by state by default
          }}
          mantineToolbarAlertBannerBadgeProps={{ color: 'primary' }}
          mantineTableContainerProps={{ style: { maxHeight: 700 } }}
        />
      );
    };
    
    export default Example;

    Manual Grouping

    Manual Grouping means that the data that you pass to the table is already grouped and aggregated, and you do not want Mantine 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.