# Row drag and drop

> Reorder rows by pointer or keyboard, drag several rows, drop into another grid or a custom element, with cancelable events and persisted order.

Canonical: https://salmonui.dev/docs/data-grid/row-drag

`rowDrag` adds a drag handle column; dragging a handle reorders the rows.
Selection is not required. `api.moveRows(rowIds, toIndex)`
moves rows by data row index; it also takes
`{ targetRowId, position: 'before' | 'after' | 'into' }` to place the rows
next to a row. Local data is
reordered in place; a data source receives the move through `write()`, and
`rowDrag.orderField` writes new order values to a field so a server can
persist the order.

```tsx
<DataGrid aria-label="Tasks" data={tasks} columns={columns} rowDrag={{ targetId: 'done' }} onRowDrop={(e) => save(e.rowIds, e.toIndex)} />
<DataGrid aria-label="Done" id="done" data={[]} columns={columns} rowDrag />
```

## Targets

`rowDrag.targetId` names another grid (by its `id`) that receives the
dragged rows: the target adds them and the source removes them.
When the id names any other element, dropping on it ends the drag without
moving rows, and `onRowDrop` carries the rows and the `target` element.
Dragging a selected row drags every selected row.
Grids exchange rows through a registry shared by every `DataGrid` of the
page; pass `rowDrag.handoff` (from `createRowDragHandoff()`) to give a set of
grids their own.

## Events

`onRowDragStart` and `onBeforeRowDrop` cancel with `preventDefault()`;
`onRowDrag` fires at most once per animation frame while the target
changes; `onRowDrop` follows the drop. Each carries `rowIds`,
`rows()`, `fromIndex`, `toIndex`, the target row and side (`targetRowId`,
`position`), `valid`, `reason`, `targetGridId` and the `target` element.
`renderRowDragPreview` replaces the preview and receives `{ rowIds, rows }`.

## Rules

Drops onto a dragged row, into a sorted grid (unless sorted ascending by
`orderField`) or into another group are invalid; `rowDrag.acrossGroups`
allows group changes and rewrites the grouped values. Rows are
moved by id over every loaded row, so dragging works with virtualization
and auto-scrolls at the edges. Alt+Shift+ArrowUp and
Alt+Shift+ArrowDown move the focused (or selected) rows by keyboard.
Escape cancels a pointer drag.

Row drag works with row pinning and with hierarchy:

- Pinned rows (row pinning) are neither drag sources nor drop
  targets: their place comes from pinning and the sort, not from the row
  order. They show no drag handle, a pointer over them is an invalid target
  (`reason: 'pinnedRow'`), a selected pinned row stays behind when the
  selection is dragged, and `moveRows` / keyboard moves never move a pinned
  row or place a row above the first scrolling row. Data indexes
  (`fromIndex`, `toIndex`, `moveRows`) count the scrolling rows only. With
  `orderField`, pinned rows keep their order values.
- A child grid (`childGrid` with its own `rowDrag`) reorders its own rows
  only. Its drags and events stay in the child: releasing a child row over
  the parent grid drops nothing, and the parent's row drag ignores the rows
  of nested child grids. To move rows between grids, use `rowDrag.targetId`.

### Live demo: Row drag and drop

Live demo: https://salmonui.dev/demos/data-grid/row-drag

Reorder rows by the drag handle or the keyboard, drag the selected rows together, and move rows into a second grid, with cancelable drop events.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridColumn, type DataGridRowDragEvent } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const backlog = createOrders(500, 3);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'priority', header: 'Priority', width: 100 },
];

export default function RowDragDemo() {
  const [log, push] = useEventLog();
  const [locked, setLocked] = useState(false);
  const record = (event: DataGridRowDragEvent<Order>) => {
    if (event.type === 'beforeRowDrop' && locked) {
      event.preventDefault();
      push('drop cancelled');
      return;
    }
    if (event.type === 'rowDrop') {
      const where = event.targetGridId ?? (event.target?.id || 'outside');
      push(`${event.rowIds.join(', ')} → ${where}${event.toIndex >= 0 ? ` at ${event.toIndex}` : ''} (${event.source})`);
    }
  };
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={locked} onCheckedChange={(checked) => setLocked(checked)}>
          Cancel drops
        </Checkbox>
      </div>
      <div className="demo-columns">
        <DataGrid<Order>
          id="row-drag-backlog"
          aria-label="Backlog"
          data={backlog}
          columns={columns}
          height={380}
          selection={{ multiple: true }}
          rowDrag={{ targetId: 'row-drag-sprint' }}
          onBeforeRowDrop={record}
          onRowDrop={record}
        />
        <DataGrid<Order> id="row-drag-sprint" aria-label="Sprint" data={[]} columns={columns} height={380} rowDrag onRowDrop={record} />
      </div>
      <p className="demo-status">
        Drag the grip to reorder, or into the Sprint grid; select several rows to drag them together. Alt+Shift+Up / Down moves the focused row.
      </p>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridRowDrag`](https://salmonui.dev/docs/reference/data-grid/DataGridRowDrag) lists
the `rowDrag` options,
[`DataGridRowDragEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridRowDragEvent)
the event payload,
[`DataGridRowDragPreviewContext`](https://salmonui.dev/docs/reference/data-grid/DataGridRowDragPreviewContext)
the preview context and [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
`moveRows`.

### Live demo: Drop targets and persisted order

Live demo: https://salmonui.dev/demos/data-grid/row-drag-targets

A ranked list whose drops write new rank values through dataSource.write, and an inbox whose rows drop onto a custom archive element.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { createLocalDataSource, type DataSource } from '@salmonui/data-grid/engine';
import { type WriteRequest } from '@salmonui/core/data';
import { DataGrid, type DataGridColumn, type DataGridSorting } from '@salmonui/data-grid';
import { EventLog, useDemoStore, useEventLog } from '../../components/demo-kit';

interface Task {
  readonly id: string;
  readonly title: string;
  readonly rank: number;
}

const TITLES = ['Write release notes', 'Fix the login redirect', 'Review the pricing page', 'Book the team offsite', 'Answer support mail', 'Update the onboarding guide', 'Plan the next milestone', 'Clean up the shared drive'];

const columns: DataGridColumn<Task>[] = [
  { field: 'id', header: 'Task', primaryKey: true, width: 90 },
  { field: 'title', header: 'Title', width: 230 },
  { field: 'rank', header: 'Rank', type: 'number', align: 'end', width: 90 },
];

// Sorted ascending by the order field: drops stay valid.
const byRank: DataGridSorting = { sortBy: [{ field: 'rank', direction: 'asc' }] };

/** A "server" that persists the rank values a drop writes. */
function createRankedSource(push: (entry: string) => void): DataSource<Task> {
  const store = createLocalDataSource<Task>(
    TITLES.map((title, i) => ({ id: `T-${i + 1}`, title, rank: (i + 1) * 10 })),
    { getRowId: (row) => row.id },
  );
  return {
    mode: 'local',
    read: (request) => store.read(request),
    subscribe: (listener) => store.subscribe(listener),
    capabilities: { write: true },
    write(request: WriteRequest<Task>) {
      const ranks = request.changed.map((c) => `${c.rowId}.rank=${c.row.rank}`).join(', ');
      push(`write: moved ${request.moved?.rowIds.join(', ') ?? '-'}; changed ${ranks || '-'}`);
      return store.write(request);
    },
  };
}

export default function RowDragTargetsDemo() {
  const [log, push] = useEventLog();
  const [source] = useState(() => createRankedSource(push));
  const [inbox, inboxStore] = useDemoStore<readonly Task[]>(TITLES.slice(0, 5).map((title, i) => ({ id: `M-${i + 1}`, title: `Mail: ${title}`, rank: i })));
  const [archived, archivedStore] = useDemoStore<readonly string[]>([]);
  return (
    <>
      <div className="demo-columns">
        <DataGrid<Task>
          aria-label="Ranked tasks"
          data={source}
          columns={columns}
          sorting={byRank}
          height={320}
          locale="en-US"
          rowDrag={{ orderField: 'rank' }}
          onRowDrop={(e) => push(`ranked drop: ${e.rowIds.join(', ')} at ${e.toIndex}`)}
        />
        <div>
          <DataGrid<Task>
            aria-label="Inbox"
            data={inbox}
            columns={columns.slice(0, 2)}
            height={240}
            locale="en-US"
            rowDrag={{ targetId: 'row-drag-archive' }}
            onRowDrop={(e) => {
              // A custom element target: the grid moves nothing; the app decides.
              if (e.targetGridId !== null || e.target?.closest('#row-drag-archive') == null) return;
              const ids = new Set(e.rowIds);
              inboxStore.set((rows) => rows.filter((row) => !ids.has(row.id)));
              archivedStore.set((list) => [...list, ...e.rowIds]);
              push(`archived ${e.rowIds.join(', ')} (dropped on #row-drag-archive)`);
            }}
          />
          <div id="row-drag-archive" className="demo-drop-zone" aria-label="Archive drop zone">
            Archive: drop inbox rows here {archived.length ? `(${archived.join(', ')})` : ''}
          </div>
        </div>
      </div>
      <EventLog entries={log} />
    </>
  );
}
```
