---
title: "Drag & Drop"
framework: react
version: "36.1.0"
---

# Drag & Drop

Drag & Drop is concerned with moving data around an application, or between applications, using the operating system drag and drop support. When using drag and drop, data is moved or copied around using MIME types in a way similar to using the clipboard.

Native drag and drop is typically used for moving data between applications, e.g. moving a URL from an email into a web browser to open the URL, or moving a file from a file explorer application to a text editor application. Native drag and drop is not typically used for operating on data inside an application. Native drag and drop is similar to clipboard functionality, e.g. data must be represented as MIME types and objects cannot be passed by reference (the data must be converted to a MIME type and copied).

This section outlines how the grid fits in with native operating system drag and drop. It is assumed the reader is familiar with how drag and drop works. If not, refer to one of the following introductions:

- [W3C Schools](https://www.w3schools.com/html/html5_draganddrop.asp)
- [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API)

> **Note**
>
> This feature should be used when you need to export Grid Data to an external application or when browser drag events need to be used because there is no way to know where content might be dropped. For all basic scenarios such as dragging data between elements in the same page or grid to grid, the grid implements its own drag and drop separate to the operating system's drag and drop. It is used internally by the grid for [Row Dragging](https://www.ag-grid.com/react-data-grid/row-dragging/) (for reordering rows) and for column dragging (e.g. re-ordering columns or moving columns in the [Column Tool Panel](https://www.ag-grid.com/react-data-grid/tool-panel-columns/)). The grid uses its own implementation in these instances as it needs finer control over the data than native browser drag & drop supports. For example, the native d&d does not provide access to the dragged item until after the drag operation is complete.

## Enable Drag Source

To allow dragging from the grid, set the property `dndSource=true` on one of the columns. This will result in the column having a drag handle displayed. When the dragging starts, the grid will by default create a JSON representation of the data and set this as MIME types `application/json` and also `text/plain`.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `dndSource` | `boolean \| DndSourceCallback` |  | `false` | `boolean` or `Function`. Set to `true` (or return `true` from function) to allow dragging for native drag and drop. Module: [`DragAndDropModule`](https://www.ag-grid.com/react-data-grid/modules/). |

In the example below, note the following:

- The first column has `dndSource=true`, so staring a mouse drag on a cell in the first column will start a drag operation.
- When the data is dragged to the drop zone, the drop zone will display the received JSON. This is because the drop zone is programmed to accept `application/json` MIME types.
- You can also drag to other applications outside of the browser. For example, some text editors (eg Sublime Text) or word processors (eg Microsoft Word) will accept the drag based on the `text/plain` MIME type. You can test this by dragging a cell to e.g. Microsoft Word.

#### Simple

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DragAndDropModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowClassRules,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  DragAndDropModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { valueGetter: "'Drag'", dndSource: true },
    { field: "id" },
    { field: "color" },
    { field: "value1" },
    { field: "value2" },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 80,
      filter: true,
    };
  }, []);
  const rowClassRules = useMemo<RowClassRules>(() => {
    return {
      "red-row": 'data.color == "Red"',
      "green-row": 'data.color == "Green"',
      "blue-row": 'data.color == "Blue"',
    };
  }, []);

  const onDragOver = useCallback((event: any) => {
    const dragSupported = event.dataTransfer.length;
    if (dragSupported) {
      event.dataTransfer.dropEffect = "move";
    }
    event.preventDefault();
  }, []);

  const onDrop = useCallback((event: any) => {
    const jsonData = event.dataTransfer.getData("application/json");
    const eJsonRow = document.createElement("div");
    eJsonRow.classList.add("json-row");
    eJsonRow.innerText = jsonData;
    const eJsonDisplay = document.querySelector("#eJsonDisplay")!;
    eJsonDisplay.appendChild(eJsonRow);
    event.preventDefault();
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="outer">
          <div className="grid-col">
            <div style={gridStyle}>
              <AgGridReact
                rowData={rowData}
                columnDefs={columnDefs}
                defaultColDef={defaultColDef}
                rowClassRules={rowClassRules}
                rowDragManaged={true}
              />
            </div>
          </div>

          <div
            className="drop-col"
            onDragOver={() => onDragOver(event)}
            onDrop={() => onDrop(event)}
          >
            <span id="eDropTarget" className="drop-target">
              {" "}
              ==&gt; Drop to here{" "}
            </span>
            <div id="eJsonDisplay" className="json-display"></div>
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Simple](https://www.ag-grid.com/examples/drag-and-drop/simple/reactFunctionalTs)

## Dragging Between Grids

It is possible to drag rows between two instances of AG Grid. The drag is done exactly like the simple case described above. The drop is done as demonstrated in the example below.

In the example below, note the following:

- Rows can be dragged from one grid to the other grid. When the row is received, it is **not** removed from the first grid. This is the choice of the example. The example could equally have removed from the other grid.
- If the row is already present in the grid, it will not be added twice. Again this is the choice of the example.
- Rows can be removed from both grids by dragging the row to the 'Trash' drop zone.
- New rows can be created by dragging out from red, green and blue 'Create' draggable areas.

#### Two Grids

```tsx
'use client';
import React, { StrictMode, useRef } from "react";
import { createRoot } from "react-dom/client";

import type {
  ColDef,
  GridApi,
  GridOptions,
  GridReadyEvent,
} from "ag-grid-community";
import {
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  DragAndDropModule,
  RowApiModule,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { AgGridProvider, AgGridReact } from "ag-grid-react";

import "./styles.css";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  DragAndDropModule,
  ClientSideRowModelApiModule,
  RowApiModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
];

const baseDefaultColDef: ColDef = {
  flex: 1,
  filter: true,
};

const baseGridOptions: GridOptions = {
  getRowId: (params) => {
    return String(params.data.id);
  },
  rowClassRules: {
    "red-row": 'data.color == "Red"',
    "green-row": 'data.color == "Green"',
    "blue-row": 'data.color == "Blue"',
  },
  rowDragManaged: true,
};

const baseColumnDefs: ColDef[] = [
  { field: "id", dndSource: true, width: 90 },
  { field: "color" },
  { field: "value1" },
  { field: "value2" },
];

const leftGridOptions: GridOptions = {
  ...baseGridOptions,
  columnDefs: [...baseColumnDefs],
  defaultColDef: {
    ...baseDefaultColDef,
  },
};

const rightGridOptions: GridOptions = {
  ...baseGridOptions,
  columnDefs: [...baseColumnDefs],
  defaultColDef: {
    ...baseDefaultColDef,
  },
};

let nextRowId = 100;

const GridExample = () => {
  const leftGridRef = useRef<AgGridReact>(null);
  const rightGridRef = useRef<AgGridReact>(null);

  const onLeftGridReady = (params: GridReadyEvent) => {
    params.api.setGridOption("rowData", createLeftRowData());
  };

  const onRightGridReady = (params: GridReadyEvent) => {
    params.api.setGridOption("rowData", []);
  };

  const createLeftRowData = () => ["Red", "Green", "Blue"].map(createDataItem);

  const createDataItem = (color: string) => {
    const newDataItem = {
      id: nextRowId++,
      color: color,
      value1: Math.floor(window.agRandom() * 100),
      value2: Math.floor(window.agRandom() * 100),
    };

    return newDataItem;
  };

  const binDragOver = (event: any) => {
    const dragSupported =
      event.dataTransfer.types.indexOf("application/json") >= 0;
    if (dragSupported) {
      event.dataTransfer.dropEffect = "move";
      event.preventDefault();
    }
  };

  const binDrop = (event: any) => {
    event.preventDefault();
    const jsonData = event.dataTransfer.getData("application/json");
    const data = JSON.parse(jsonData);

    // if data missing or data has no id, do nothing
    if (!data || data.id == null) {
      return;
    }

    const transaction = {
      remove: [data],
    };

    const rowIsInLeftGrid = !!leftGridRef.current!.api.getRowNode(data.id);
    if (rowIsInLeftGrid) {
      leftGridRef.current!.api.applyTransaction(transaction);
    }

    const rowIsInRightGrid = !!rightGridRef.current!.api.getRowNode(data.id);
    if (rowIsInRightGrid) {
      rightGridRef.current!.api.applyTransaction(transaction);
    }
  };

  const dragStart = (color: string, event: any) => {
    const newItem = createDataItem(color);
    const jsonData = JSON.stringify(newItem);

    event.dataTransfer.setData("application/json", jsonData);
  };

  const gridDragOver = (event: any) => {
    const dragSupported = event.dataTransfer.types.length;

    if (dragSupported) {
      event.dataTransfer.dropEffect = "copy";
      event.preventDefault();
    }
  };

  const gridDrop = (grid: string, event: any) => {
    event.preventDefault();

    const jsonData = event.dataTransfer.getData("application/json");
    const data = JSON.parse(jsonData);

    // if data missing or data has no it, do nothing
    if (!data || data.id == null) {
      return;
    }

    const gridApi: GridApi =
      grid === "left" ? leftGridRef.current!.api : rightGridRef.current!.api;

    // do nothing if row is already in the grid, otherwise we would have duplicates
    const rowAlreadyInGrid = !!gridApi.getRowNode(data.id);
    if (rowAlreadyInGrid) {
      console.log("not adding row to avoid duplicates in the grid");
      return;
    }

    const transaction = {
      add: [data],
    };
    gridApi.applyTransaction(transaction);
  };

  return (
    <AgGridProvider modules={modules}>
      <div className="outer">
        <div
          style={{ height: "100%" }}
          className="inner-col"
          onDragOver={gridDragOver}
          onDrop={(e) => gridDrop("left", e)}
        >
          <AgGridReact
            ref={leftGridRef}
            gridOptions={leftGridOptions}
            onGridReady={onLeftGridReady}
          />
        </div>

        <div className="inner-col factory-panel">
          <span
            id="eBin"
            onDragOver={binDragOver}
            onDrop={binDrop}
            className="factory factory-bin"
          >
            <i className="far fa-trash-alt">
              <span className="filename"> Trash - </span>
            </i>
            Drop target to destroy row
          </span>
          <span
            draggable="true"
            onDragStart={(e) => dragStart("Red", e)}
            className="factory factory-red"
          >
            <i className="far fa-plus-square">
              <span className="filename"> Create - </span>
            </i>
            Drag source for new red item
          </span>
          <span
            draggable="true"
            onDragStart={(e) => dragStart("Green", e)}
            className="factory factory-green"
          >
            <i className="far fa-plus-square">
              <span className="filename"> Create - </span>
            </i>
            Drag source for new green item
          </span>
          <span
            draggable="true"
            onDragStart={(e) => dragStart("Blue", e)}
            className="factory factory-blue"
          >
            <i className="far fa-plus-square">
              <span className="filename"> Create - </span>
            </i>
            Drag source for new blue item
          </span>
        </div>

        <div
          style={{ height: "100%" }}
          className="inner-col"
          onDragOver={gridDragOver}
          onDrop={(e) => gridDrop("right", e)}
        >
          <AgGridReact
            ref={rightGridRef}
            gridOptions={rightGridOptions}
            onGridReady={onRightGridReady}
          />
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Two Grids](https://www.ag-grid.com/examples/drag-and-drop/two-grids/reactFunctionalTs)

Note that there is no specific drop zone logic in the grid. This was done on purpose after analysis.

On initial analysis, consideration was given to exposing callbacks or firing events in the grid for the drop zone relevant events e.g. `onDragEnter`, `onDragExit` etc. However this did not add any additional value given that the developer can easily add such event listeners to the grid div directly.

Given that the grid would be simply exposing the underlying events / callbacks rather than doing any processing itself, it would not be adding any value and so providing such callbacks would just be adding a layer of useless logic.

## Custom Drag Data

It is possible that a JSON representation of the data is not what is required as the drag data.

To provide alternative drag data, use the `dndSourceOnRowDrag` callback on the column definition. This allows specific processing by the application for the `rowdrag` even rather than the default grid behaviour.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `dndSourceOnRowDrag` | `DndSourceOnRowDragFunc` |  |  | Function to allow custom drag functionality for native drag and drop. Module: [`DragAndDropModule`](https://www.ag-grid.com/react-data-grid/modules/). |

The example below is identical to the first example on this page with the addition of custom drag data. Note the following:

- The draggable column also has `dndSourceOnRowDrag` set.
- The `onRowDrag` method provides an alternative piece of drag data to be set into the drag event.
- The data dragged also includes row state such as whether the rows is selected or not.

#### Custom Drag Data

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DndSourceOnRowDragParams,
  DragAndDropModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowClassRules,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  DragAndDropModule,
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
];

function onRowDrag(params: DndSourceOnRowDragParams) {
  // create the data that we want to drag
  const rowNode = params.rowNode;
  const e = params.dragEvent;
  const jsonObject = {
    grid: "GRID_001",
    operation: "Drag on Column",
    rowId: rowNode.data.id,
    selected: rowNode.isSelected(),
  };
  const jsonData = JSON.stringify(jsonObject);
  e.dataTransfer!.setData("application/json", jsonData);
  e.dataTransfer!.setData("text/plain", jsonData);
}

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 80,
      filter: true,
    };
  }, []);
  const rowClassRules = useMemo<RowClassRules>(() => {
    return {
      "red-row": 'data.color == "Red"',
      "green-row": 'data.color == "Green"',
      "blue-row": 'data.color == "Blue"',
    };
  }, []);
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    {
      valueGetter: "'Drag'",
      dndSource: true,
      dndSourceOnRowDrag: onRowDrag,
    },
    { field: "id" },
    { field: "color" },
    { field: "value1" },
    { field: "value2" },
  ]);

  const onDragOver = useCallback((event: any) => {
    const dragSupported = event.dataTransfer.types.length;
    if (dragSupported) {
      event.dataTransfer.dropEffect = "move";
    }
    event.preventDefault();
  }, []);

  const onDrop = useCallback((event: any) => {
    event.preventDefault();
    const jsonData = event.dataTransfer.getData("application/json");
    const eJsonRow = document.createElement("div");
    eJsonRow.classList.add("json-row");
    eJsonRow.innerText = jsonData;
    const eJsonDisplay = document.querySelector("#eJsonDisplay")!;
    eJsonDisplay.appendChild(eJsonRow);
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="outer">
          <div className="grid-col">
            <div style={gridStyle}>
              <AgGridReact
                rowData={rowData}
                defaultColDef={defaultColDef}
                rowClassRules={rowClassRules}
                rowDragManaged={true}
                columnDefs={columnDefs}
              />
            </div>
          </div>

          <div
            className="drop-col"
            onDragOver={() => onDragOver(event)}
            onDrop={() => onDrop(event)}
          >
            <span id="eDropTarget" className="drop-target">
              {" "}
              ==&gt; Drop to here{" "}
            </span>
            <div id="eJsonDisplay" className="json-display"></div>
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Custom Drag Data](https://www.ag-grid.com/examples/drag-and-drop/custom-drag-data/reactFunctionalTs)

## Custom Drag Component

Drag and drop is a complex application-level requirement. As such, a component (the grid) can't propose a drag and drop solution that is appropriate for all applications. For this reason, if the application has drag and drop requirements, you would likely want to implement a custom [Cell Renderer](https://www.ag-grid.com/react-data-grid/component-cell-renderer/) specifically for your needs.

The example below shows a custom drag and drop cell renderer. Note the following:

- The dragging works similar to before, rows are dragged from the left grid to the right drop zone.
- The grid does not provide the dragging. Instead, the example's cell renderer implements the drag logic.

#### Custom Drag Component

```tsx
"use client";

import React, {
  useCallback,
  useMemo,
  useRef,
  useState,
  StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  RowClassRules,
  RowDragModule,
  RowStyleModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";
import DragSourceRenderer from "./dragSourceRenderer.tsx";

if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

const modules = [
  TextFilterModule,
  RowDragModule,
  RowStyleModule,
  ClientSideRowModelModule,
];

const GridExample = () => {
  const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
  const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
  const [rowData, setRowData] = useState<any[]>(getData());
  const rowClassRules = useMemo<RowClassRules>(() => {
    return {
      "red-row": 'data.color == "Red"',
      "green-row": 'data.color == "Green"',
      "blue-row": 'data.color == "Blue"',
    };
  }, []);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      width: 80,
      filter: true,
    };
  }, []);
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { cellRenderer: DragSourceRenderer, minWidth: 100 },
    { field: "id" },
    { field: "color" },
    { field: "value1" },
    { field: "value2" },
  ]);

  const onDragOver = useCallback((event: any) => {
    const types = event.dataTransfer.types;
    const dragSupported = types.length;
    if (dragSupported) {
      event.dataTransfer.dropEffect = "move";
    }
    event.preventDefault();
  }, []);

  const onDrop = useCallback((event: any) => {
    event.preventDefault();
    const textData = event.dataTransfer.getData("text/plain");
    const eJsonRow = document.createElement("div");
    eJsonRow.classList.add("json-row");
    eJsonRow.innerText = textData;
    const eJsonDisplay = document.querySelector("#eJsonDisplay")!;
    eJsonDisplay.appendChild(eJsonRow);
  }, []);

  return (
    <AgGridProvider modules={modules}>
      <div style={containerStyle}>
        <div className="outer">
          <div className="grid-col">
            <div style={gridStyle}>
              <AgGridReact
                rowData={rowData}
                rowClassRules={rowClassRules}
                defaultColDef={defaultColDef}
                rowDragManaged={true}
                columnDefs={columnDefs}
              />
            </div>
          </div>

          <div
            className="drop-col"
            onDragOver={() => onDragOver(event)}
            onDrop={() => onDrop(event)}
          >
            <span id="eDropTarget" className="drop-target">
              {" "}
              ==&gt; Drop to here{" "}
            </span>
            <div id="eJsonDisplay" className="json-display"></div>
          </div>
        </div>
      </div>
    </AgGridProvider>
  );
};

const root = createRoot(document.getElementById("root")!);
root.render(
  <StrictMode>
    <GridExample />
  </StrictMode>,
);
```

[Live example: Custom Drag Component](https://www.ag-grid.com/examples/drag-and-drop/custom-drag-comp/reactFunctionalTs)
