Examples › Column dragging and toggling

Mantine DataTable lets users reorder columns by drag-and-drop and show or hide them as needed. The column order and visibility are persisted in the browser’s local storage, so they survive page reloads. These features were originally contributed by Giovambattista Fazioli — thanks for the outstanding work!

Column drag-and-drop reordering

Name
Street address
City
State
Feest, Bogan and Herzog21716 Ratke DriveStromanportWY
Cummerata - Kuhlman6389 Dicki StreamSouth GateNH
Goyette Inc8873 Mertz RapidDorthysideID
Runte Inc2996 Ronny MountMcAllenMA
Goldner, Rohan and Lehner632 Broadway AvenueNorth LouieWY
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburghKS
Rau - O'Hara7508 Lansdowne RoadShieldsboroughMI
Tillman - Jacobi57918 Gwendolyn CirclesSheridanportMI
Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburghCA
Shanahan, Robel and Beier378 Berta CrescentWest GerryKS
Kling - McLaughlin8346 Kertzmann SquareSouth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
No records

In order to enable column dragging you’ll have to:

  • add a storeColumnsKey: 'your_key' property to the DataTable (the column order is persisted in local storage under this key);
  • add a draggable: true property to each dragging candidate column;
  • use the useDataTableColumns() hook with the same key to get the effective (sorted) columns and pass them to the DataTable.
'use client';

import { DataTable, useDataTableColumns } from 'mantine-datatable';
import { Button, Group, Stack } from '@mantine/core';
import { type Company, companies } from '~/data';

export default function DraggingExample() {
  const key = 'draggable-example';

  const { effectiveColumns, resetColumnsOrder } = useDataTableColumns<Company>({
    key,
    columns: [
      { accessor: 'name', width: '40%', draggable: true },
      { accessor: 'streetAddress', width: '60%', draggable: true },
      { accessor: 'city', width: 160, draggable: true },
      { accessor: 'state', textAlign: 'right' },
    ],
  });

  return (
    <Stack>
      <DataTable
        withTableBorder
        withColumnBorders
        storeColumnsKey={key}
        records={companies}
        columns={effectiveColumns}
      />
      <Group justify="right">
        <Button onClick={resetColumnsOrder}>Reset Column Order</Button>
      </Group>
    </Stack>
  );
}

Draggable columns display a grip icon in their header. A column can only be dropped onto another draggable column, and is then moved to that column’s position.

Column toggling

In the example below:

  • you can toggle the first 3 columns;
  • the last column is not toggleable and will always be visible;
  • the first column is hidden by default.

Hover over a toggleable column header and click its × button to hide the column, or right-click anywhere on the table header to open a menu where you can show or hide each toggleable column.

21716 Ratke DriveStromanportWY
6389 Dicki StreamSouth GateNH
8873 Mertz RapidDorthysideID
2996 Ronny MountMcAllenMA
632 Broadway AvenueNorth LouieWY
576 Joyce WaysTyraburghKS
7508 Lansdowne RoadShieldsboroughMI
57918 Gwendolyn CirclesSheridanportMI
7057 Stanley RoadKearaburghCA
378 Berta CrescentWest GerryKS
8346 Kertzmann SquareSouth JoesphID
83462 Shazam StreetNorth JoesphID
83462 Shazam StreetNorth JoesphID
No records

In order to enable column toggling you’ll have to:

  • add a storeColumnsKey: 'your_key' property to the DataTable (the column visibility is persisted in local storage under this key);
  • add a toggleable: true property to each toggling candidate column;
  • use the useDataTableColumns() hook with the same key to get the effective columns and pass them to the DataTable.
'use client';

import { DataTable, useDataTableColumns } from 'mantine-datatable';
import { Button, Group, Stack, Text } from '@mantine/core';
import { IconBuildingCommunity, IconBuildingSkyscraper, IconMap, IconRoadSign } from '@tabler/icons-react';
import { companies } from '~/data';

export default function TogglingExample() {
  const key = 'toggleable-example';

  const { effectiveColumns, resetColumnsToggle } = useDataTableColumns({
    key,
    columns: [
      {
        accessor: 'name',
        title: (
          <Group gap={4} mt={-1}>
            <IconBuildingSkyscraper size={16} />
            <Text inherit mt={1}>
              Company
            </Text>
          </Group>
        ),
        width: '40%',
        toggleable: true,
        defaultToggle: false,
      },
      {
        accessor: 'streetAddress',
        title: (
          <Group gap={4} mt={-1}>
            <IconRoadSign size={16} />
            <Text inherit mt={1}>
              Street Address
            </Text>
          </Group>
        ),
        width: '60%',
        toggleable: true,
      },
      {
        accessor: 'city',
        title: (
          <Group gap={4} mt={-1}>
            <IconBuildingCommunity size={16} />
            <Text inherit mt={1}>
              City
            </Text>
          </Group>
        ),
        width: 160,
        toggleable: true,
      },
      {
        accessor: 'state',
        textAlign: 'right',
        title: (
          <Group justify="right">
            <IconMap size={16} />
          </Group>
        ),
      },
    ],
  });

  return (
    <Stack>
      <DataTable
        withTableBorder
        withColumnBorders
        storeColumnsKey={key}
        records={companies}
        columns={effectiveColumns}
      />
      <Group justify="right">
        <Button onClick={resetColumnsToggle}>Reset toggled columns</Button>
      </Group>
    </Stack>
  );
}

Custom column visibility controls

Besides the built-in header menu, you can build your own column visibility controls. The useDataTableColumns() hook returns the current visibility state as columnsToggle — an array of { accessor, toggleable, toggled } objects — and a setColumnsToggle() function to update it:

Feest, Bogan and Herzog21716 Ratke DriveStromanport
Cummerata - Kuhlman6389 Dicki StreamSouth Gate
Goyette Inc8873 Mertz RapidDorthyside
Runte Inc2996 Ronny MountMcAllen
Goldner, Rohan and Lehner632 Broadway AvenueNorth Louie
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburgh
Rau - O'Hara7508 Lansdowne RoadShieldsborough
Tillman - Jacobi57918 Gwendolyn CirclesSheridanport
Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburgh
Shanahan, Robel and Beier378 Berta CrescentWest Gerry
Kling - McLaughlin8346 Kertzmann SquareSouth Joesph
Jogi - McLaughlin83462 Shazam StreetNorth Joesph
Jogi - McLaughlin83462 Shazam StreetNorth Joesph
No records
'use client';

import { DataTable, humanize, useDataTableColumns } from 'mantine-datatable';
import { Button, Checkbox, Group, Stack } from '@mantine/core';
import { type Company, companies } from '~/data';

export default function TogglingWithCustomControlsExample() {
  const key = 'toggling-with-custom-controls-example';

  const { effectiveColumns, columnsToggle, setColumnsToggle, resetColumnsToggle } = useDataTableColumns<Company>({
    key,
    columns: [
      { accessor: 'name', width: '40%' },
      { accessor: 'streetAddress', width: '60%', toggleable: true },
      { accessor: 'city', width: 160, toggleable: true },
      { accessor: 'state', textAlign: 'right', toggleable: true, defaultToggle: false },
    ],
  });

  return (
    <Stack>
      <Group justify="space-between">
        <Group>
          {columnsToggle
            // 👇 only show controls for toggleable columns
            .filter(({ toggleable }) => toggleable)
            .map(({ accessor, toggled }) => (
              <Checkbox
                key={accessor}
                label={humanize(accessor)}
                checked={toggled}
                onChange={(e) => {
                  const { checked } = e.currentTarget;
                  setColumnsToggle(
                    columnsToggle.map((column) =>
                      column.accessor === accessor ? { ...column, toggled: checked } : column
                    )
                  );
                }}
              />
            ))}
        </Group>
        <Button size="compact-sm" variant="light" onClick={resetColumnsToggle}>
          Reset
        </Button>
      </Group>
      <DataTable
        withTableBorder
        withColumnBorders
        storeColumnsKey={key}
        records={companies}
        columns={effectiveColumns}
      />
    </Stack>
  );
}

Adding and removing columns at runtime

You can add or remove columns at runtime by simply changing the array of columns you pass to the hook. The persisted order and visibility state is automatically kept in sync with the current column definitions: state for removed columns is discarded, and newly added columns are appended with their default settings.

21716 Ratke DriveStromanportWY
6389 Dicki StreamSouth GateNH
8873 Mertz RapidDorthysideID
2996 Ronny MountMcAllenMA
632 Broadway AvenueNorth LouieWY
576 Joyce WaysTyraburghKS
7508 Lansdowne RoadShieldsboroughMI
57918 Gwendolyn CirclesSheridanportMI
7057 Stanley RoadKearaburghCA
378 Berta CrescentWest GerryKS
8346 Kertzmann SquareSouth JoesphID
83462 Shazam StreetNorth JoesphID
83462 Shazam StreetNorth JoesphID
No records
'use client';

import type { DataTableColumn } from 'mantine-datatable';
import { DataTable, useDataTableColumns } from 'mantine-datatable';
import { Button, Group, Stack, Text } from '@mantine/core';
import { IconBuildingCommunity, IconBuildingSkyscraper, IconMap, IconRoadSign } from '@tabler/icons-react';
import { useRef, useState } from 'react';
import { companies } from '~/data';

export default function DynamicColumnExample() {
  const key = 'dynamic-column-example';

  const [columns, setColumns] = useState<DataTableColumn[]>([
    {
      accessor: 'name',
      title: (
        <Group gap={4} mt={-1}>
          <IconBuildingSkyscraper size={16} />
          <Text inherit mt={1}>
            Company
          </Text>
        </Group>
      ),
      width: '40%',
      toggleable: true,
      defaultToggle: false,
    },
    {
      accessor: 'streetAddress',
      title: (
        <Group gap={4} mt={-1}>
          <IconRoadSign size={16} />
          <Text inherit mt={1}>
            Street Address
          </Text>
        </Group>
      ),
      width: '60%',
      toggleable: true,
    },
    {
      accessor: 'city',
      title: (
        <Group gap={4} mt={-1}>
          <IconBuildingCommunity size={16} />
          <Text inherit mt={1}>
            City
          </Text>
        </Group>
      ),
      width: 160,
      toggleable: true,
    },
    {
      accessor: 'state',
      textAlign: 'right',
      title: (
        <Group justify="right">
          <IconMap size={16} />
        </Group>
      ),
    },
  ]);

  const initialColumns = useRef(columns);

  const { effectiveColumns, resetColumnsToggle, columnsToggle, setColumnsToggle } = useDataTableColumns({
    key,
    columns,
  });

  function resetAll() {
    setColumns(initialColumns.current);
    resetColumnsToggle();
  }

  // Show / hide the Mission Statement column. If it's currently hidden via the
  // header X (but still in `columns`), un-hide it; otherwise add or remove the
  // column definition itself.
  function toggleColumnMissionStatement() {
    const inColumns = columns.some((col) => col.accessor === 'missionStatement');
    const hiddenByToggle =
      inColumns && columnsToggle?.find((t) => t.accessor === 'missionStatement')?.toggled === false;

    if (hiddenByToggle) {
      setColumnsToggle(columnsToggle.map((t) => (t.accessor === 'missionStatement' ? { ...t, toggled: true } : t)));
      return;
    }

    const newColumns = columns.filter((col) => col.accessor !== 'missionStatement');
    if (columns.length === newColumns.length) {
      newColumns.push({
        accessor: 'missionStatement',
        title: (
          <Group gap={4} mt={-1} wrap="nowrap">
            <IconBuildingSkyscraper size={16} />
            <Text inherit mt={1}>
              Mission Statement
            </Text>
          </Group>
        ),
        width: '40%',
        toggleable: true,
        defaultToggle: true,
      });
    }
    setColumns(newColumns);
  }

  return (
    <Stack>
      <Group>
        <Button onClick={toggleColumnMissionStatement}>Toggle Mission Statement column</Button>
      </Group>
      <DataTable
        withTableBorder
        withColumnBorders
        storeColumnsKey={key}
        records={companies}
        columns={effectiveColumns}
      />
      <Group justify="right">
        <Button onClick={resetAll}>Reset toggled columns</Button>
      </Group>
    </Stack>
  );
}

Resetting the column state from a context menu

The reset functions returned by the hook can be called from anywhere — for example, from a row context menu. Right-click on any row in the example below to reset the column visibility or order:

Feest, Bogan and Herzog21716 Ratke DriveStromanportWY
Cummerata - Kuhlman6389 Dicki StreamSouth GateNH
Goyette Inc8873 Mertz RapidDorthysideID
Runte Inc2996 Ronny MountMcAllenMA
Goldner, Rohan and Lehner632 Broadway AvenueNorth LouieWY
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburghKS
Rau - O'Hara7508 Lansdowne RoadShieldsboroughMI
Tillman - Jacobi57918 Gwendolyn CirclesSheridanportMI
Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburghCA
Shanahan, Robel and Beier378 Berta CrescentWest GerryKS
Kling - McLaughlin8346 Kertzmann SquareSouth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
No records
'use client';

import { DataTable, useDataTableColumns } from 'mantine-datatable';
import { IconColumnRemove, IconColumns3 } from '@tabler/icons-react';
import { useContextMenu } from 'mantine-contextmenu';
import { companies } from '~/data';

export default function DraggingTogglingResetExample() {
  const { showContextMenu } = useContextMenu();

  const key = 'toggleable-reset-example';

  const { effectiveColumns, resetColumnsOrder, resetColumnsToggle } = useDataTableColumns({
    key,
    columns: [
      { accessor: 'name', width: '40%', toggleable: true, draggable: true },
      { accessor: 'streetAddress', width: '60%', toggleable: true, draggable: true },
      { accessor: 'city', width: 160, toggleable: true, draggable: true },
      { accessor: 'state', textAlign: 'right' },
    ],
  });

  return (
    <DataTable
      withTableBorder
      withColumnBorders
      storeColumnsKey={key}
      records={companies}
      columns={effectiveColumns}
      onRowContextMenu={({ event }) =>
        showContextMenu([
          {
            key: 'reset-toggled-columns',
            icon: <IconColumnRemove size={16} />,
            onClick: resetColumnsToggle,
          },
          {
            key: 'reset-columns-order',
            icon: <IconColumns3 size={16} />,
            onClick: resetColumnsOrder,
          },
        ])(event)
      }
    />
  );
}

Combining dragging and toggling with sorting

Column dragging and toggling work seamlessly with other features, such as sorting:

Connelly, Feest and Hodkiewicz7057 Stanley RoadKearaburghCA
Cummerata - Kuhlman6389 Dicki StreamSouth GateNH
Doyle, Hodkiewicz and O'Connell576 Joyce WaysTyraburghKS
Feest, Bogan and Herzog21716 Ratke DriveStromanportWY
Goldner, Rohan and Lehner632 Broadway AvenueNorth LouieWY
Goyette Inc8873 Mertz RapidDorthysideID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Jogi - McLaughlin83462 Shazam StreetNorth JoesphID
Kling - McLaughlin8346 Kertzmann SquareSouth JoesphID
Rau - O'Hara7508 Lansdowne RoadShieldsboroughMI
Runte Inc2996 Ronny MountMcAllenMA
Shanahan, Robel and Beier378 Berta CrescentWest GerryKS
Tillman - Jacobi57918 Gwendolyn CirclesSheridanportMI
No records
'use client';

import { DataTable, type DataTableSortStatus, useDataTableColumns } from 'mantine-datatable';
import { IconColumnRemove, IconColumns3 } from '@tabler/icons-react';
import sortBy from 'lodash/sortBy';
import { useContextMenu } from 'mantine-contextmenu';
import { useEffect, useState } from 'react';
import { type Company, companies } from '~/data';

export default function DraggingTogglingComplexExample() {
  const { showContextMenu } = useContextMenu();

  const [sortStatus, setSortStatus] = useState<DataTableSortStatus<Company>>({
    columnAccessor: 'name',
    direction: 'asc',
  });

  const [records, setRecords] = useState(sortBy(companies, 'name'));

  useEffect(() => {
    const data = sortBy(companies, sortStatus.columnAccessor) as Company[];
    setRecords(sortStatus.direction === 'desc' ? data.reverse() : data);
  }, [sortStatus]);

  const key = 'dragging-toggling-complex-example';

  const { effectiveColumns, resetColumnsOrder, resetColumnsToggle } = useDataTableColumns({
    key,
    columns: [
      { accessor: 'name', width: '40%', toggleable: true, draggable: true, sortable: true },
      { accessor: 'streetAddress', width: '60%', toggleable: true, draggable: true },
      { accessor: 'city', width: 160, toggleable: true, draggable: true },
      { accessor: 'state', textAlign: 'right' },
    ],
  });

  return (
    <DataTable
      withTableBorder
      withColumnBorders
      storeColumnsKey={key}
      records={records}
      columns={effectiveColumns}
      sortStatus={sortStatus}
      onSortStatusChange={setSortStatus}
      onRowContextMenu={({ event }) =>
        showContextMenu([
          {
            key: 'reset-toggled-columns',
            icon: <IconColumnRemove size={16} />,
            onClick: resetColumnsToggle,
          },
          {
            key: 'reset-columns-order',
            icon: <IconColumns3 size={16} />,
            onClick: resetColumnsOrder,
          },
        ])(event)
      }
    />
  );
}

See also column resizing and pinning arbitrary columns, which rely on the same hook.

Mantine DataTable is used and trusted by