Examples › Row dragging

Mantine DataTable doesn’t include a drag-and-drop implementation of its own, but it exposes the building blocks you need to make rows draggable with a library such as @hello-pangea/dnd (support was added in this PR). Drag a row by its handle to see it in action:

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

How it works

The implementation relies on the following DataTable features:

  • tableWrapper → a function receiving the table as children and returning a React node that wraps it; use it to wrap the table in a Droppable container;
  • rowFactory → a function that lets you take over the rendering of each row. It receives an object with the current record, its index, the default rowProps (class name, style, event handlers, etc.), the row cells as children and, if you use row expansion, the expandedElement to render after the row. Use it to wrap each row in a Draggable component;
  • DataTableDraggableRow → a table row component exported by Mantine DataTable. Pass it the rowProps received by rowFactory, along with an isDragging flag. While a row is being dragged, the component fixes its cell widths to match the header cells, so that the row keeps its shape, and sets data-is-dragging="true" on it, which you can use for styling.

Since the drag handle is rendered by rowFactory in an extra cell, you’ll need to add a matching column with hiddenContent set to true, so that the header and body cells stay aligned. Giving the columns explicit widths and setting the table layout to fixed prevents them from changing size while dragging.

Here is the code:

'use client';

import type { DataTableColumn } from 'mantine-datatable';
import { DataTable, DataTableDraggableRow } from 'mantine-datatable';
import { DragDropContext, Draggable, Droppable, type DropResult } from '@hello-pangea/dnd';
import { Center, TableTd } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { IconGripVertical } from '@tabler/icons-react';
import clsx from 'clsx';
import { useState } from 'react';
import companies from '~/data/companies.json';
import classes from './RowDraggingExample.module.css';

interface RecordData {
  id: string;
  name: string;
  streetAddress: string;
  city: string;
  state: string;
  missionStatement: string;
}

export function RowDraggingExample() {
  const [records, setRecords] = useState<RecordData[]>(companies);

  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return;

    const items = Array.from(records);
    const sourceIndex = result.source.index;
    const destinationIndex = result.destination.index;
    const [reorderedItem] = items.splice(sourceIndex, 1);
    items.splice(destinationIndex, 0, reorderedItem);

    setRecords(items);
    notifications.show({
      title: 'Table reordered',
      message: `The company named “${reorderedItem.name}” has been moved from position ${sourceIndex + 1} to ${destinationIndex + 1}.`,
      color: 'blue',
    });
  };

  const columns: DataTableColumn<RecordData>[] = [
    // add empty header column for the drag handle
    { accessor: '', hiddenContent: true, width: 30 },
    { accessor: 'name', width: 150 },
    { accessor: 'streetAddress', width: 150 },
    { accessor: 'city', width: 150 },
    { accessor: 'state', width: 150 },
  ];

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <DataTable<RecordData>
        columns={columns}
        records={records}
        height={400}
        withTableBorder
        withColumnBorders
        tableWrapper={({ children }) => (
          <Droppable droppableId="datatable">
            {(provided) => (
              <div {...provided.droppableProps} ref={provided.innerRef}>
                {children}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        )}
        styles={{ table: { tableLayout: 'fixed' } }}
        rowFactory={({ record, index, rowProps, children }) => (
          <Draggable key={record.id} draggableId={record.id} index={index}>
            {(provided, snapshot) => (
              <DataTableDraggableRow
                isDragging={snapshot.isDragging}
                {...rowProps}
                // 👇 custom class name for styling
                className={clsx(rowProps.className, classes.draggableRow)}
                {...provided.draggableProps}
              >
                <TableTd>
                  {/** 👇 custom drag handle */}
                  <Center {...provided.dragHandleProps} ref={provided.innerRef}>
                    <IconGripVertical size={16} />
                  </Center>
                </TableTd>
                {children}
              </DataTableDraggableRow>
            )}
          </Draggable>
        )}
      />
    </DragDropContext>
  );
}

Head over to the next example to discover more features.

Mantine DataTable is used and trusted by