Skip to main content

Drag and Drop

Reorder list rows, table rows, and tree items by pointer or keyboard with the optional dnd kit adapter.

View as Markdown

Drag and drop reordering comes from an optional adapter in moraine/dnd. Components have no drag props. A sortable composes through the render prop that already owns each row element, so it adds nothing to components that are not reordered.

Adapter Use it with
createListSortable List, DataTable rows, and any flat collection whose row elements you render
createTreeSortable Tree items
createSortable Custom collections that need their own drop rules

Installation#

Only moraine/dnd imports @dnd-kit/dom. The main moraine entry does not, so apps that do not reorder anything do not need the package.

List#

import { createSignal } from 'solid-js'
import { List } from 'moraine'
import { createListSortable } from 'moraine/dnd'

const [items, setItems] = createSignal(initialItems)
const sortable = createListSortable({
  items,
  onReorder: (event) => setItems(event.items),
})

<sortable.Provider>
  <List
    items={items()}
    itemRender={(context) => {
      const row = sortable.useRow(context)
      return (
        <li {...row.props}>
          <button ref={row.handleRef} aria-label={`Reorder ${context.item.label}`}>
            ⋮⋮
          </button>
          {context.item.label}
        </li>
      )
    }}
  />
</sortable.Provider>
  • items is an accessor for the items in rendered order. The sortable reads it at drop time.
  • onReorder receives the moved item, its from and to indexes, and items, a copy of the collection with the move applied. A drop that leaves the item where it was reports nothing.
  • useRow(context) takes the row index and optional props from the render context. row.props keeps those props, composes the drag ref into their ref, and adds the drag state attributes. Spread it onto the outer row element.
  • Mount sortable.Provider once, around the component that renders the rows.

DataTable#

DataTable takes the row registration through rowProps, and a cell can render the handle with handleRefFor:

const sortable = createListSortable({
  items: () => table.getRowModel().rows,
  getId: (row) => row.id,
  onReorder: (event) => setData(event.items.map((row) => row.original)),
})

// In a column: cell: (props) => <button ref={sortable.handleRefFor(props.row.id)}>⋮⋮</button>

<sortable.Provider>
  <DataTable table={table} rowProps={(context) => sortable.useRow(context).props} />
</sortable.Provider>

Read DataTable drag to reorder rows for sorting, pagination, and sub-rows. Columns reorder the same way through headProps, with orientation: 'horizontal' and table.getVisibleLeafColumns() as items.

Tree#

createTreeSortable(tree, { onMove }) registers items through itemRender. Spread sortable.useNode(item).props onto tree.Item. Rows accept drops before, after, and, when canNest allows it, inside. Read Tree drag to move items for the drop rules, auto-expansion, and moveTreeNode. Keyboard dragging in a tree starts only from a handle, so Space and Enter on the item keep their tree behavior.

How it works#

Rows stay in place#

Rows do not move while dragging. The dragged row element follows the pointer, an inert copy of it stays in its place, and the row under the pointer is marked as the drop target:

Attribute Element Value
data-dragging Dragged row and the copy Present while it is dragged
data-dnd-dragging Row element that follows the pointer Set by dnd kit; style it, for example data-[dnd-dragging]:opacity-60
data-dnd-placeholder Copy that stays in place Set by dnd kit; the copy is inert and hidden from assistive technology
data-drop-position Row under the pointer before or after, from the pointer’s half of the row; inside for tree items that accept children

Style the drop indicator from these attributes. For example, draw a line on the matching edge:

<li
  {...row.props}
  class="data-[drop-position=before]:shadow-[inset_0_2px_0_var(--primary)] data-[drop-position=after]:shadow-[inset_0_-2px_0_var(--primary)]"
/>

Keeping rows in place lets a sortable work with rows that Solid or a virtualizer owns, and keeps row state such as focus intact until the drop. When the drag ends, the moved row slides from where it was released into its new place, also when the host renders it as a new element. Canceled drags slide back the same way. Pass dropAnimation: { duration, easing } to tune it, or false to turn it off; it is skipped under prefers-reduced-motion.

Drag handles#

Without row.handleRef, the whole row starts a drag once the mouse moves 5 pixels, or after a 200 ms press, so clicks on the row still work. Touch drags start after a 250 ms press. Pass row.handleRef to an element such as a grip button to start drags only from that element; a mouse drag from a handle starts immediately.

Keyboard#

Focus the handle, or a focusable row without one, and press Space or Enter to pick it up. Arrow keys move to the next row; the side is the direction of travel. Space, Enter, or Tab drops the row, and Escape cancels the drag. Screen readers hear dnd kit’s announcements for each step.

Virtualization#

Pass sortable.rangeExtractor to the virtualizer. It renders the visible range plus overscan, like the default extractor, and adds the dragged row while it is scrolled out of view. Dragging near the edge of the scroll container scrolls it.

createTableVirtualizer takes the same option.

const virtualizer = createListVirtualizer<Item>({
  estimateSize: () => 36,
  getItemKey: (item) => item.id,
  rangeExtractor: sortable.rangeExtractor,
})

Pass getItemKey with a stable id so measured row sizes follow their items after a move.

Options#

createSortable, createListSortable, and createTreeSortable forward these options to dnd kit:

Option Description
sensors Input sensors. An array replaces the pointer and keyboard defaults; a function receives the defaults and returns the list to use.
plugins Plugins such as announcements, auto-scroll, and drag feedback. An array replaces the defaults; a function receives them.
modifiers Movement modifiers, such as restricting the drag to one axis.
import { PointerSensor } from '@dnd-kit/dom'

// Pointer dragging only, without keyboard dragging.
const sortable = createListSortable({ items, onReorder, sensors: [PointerSensor] })

createListSortable also takes:

  • getId(item, index): a stable id, used by handleRefFor. Defaults to the index.
  • isDisabled(item, index): keeps a row from being dragged or dropped on.
  • canDrop(source, target, position): rejects a drop location before it shows an indicator.

createSortable and createListSortable also take orientation and dropAnimation. Set orientation: 'horizontal' for items laid out in a row, such as chips. before and after then come from the inline start and end halves of an item, mirrored in right-to-left layouts.

onReorder also receives the target item and the position (before or after) for data that is not a flat array. moveItem(items, from, to) returns a moved copy of an array.

Custom collections#

createSortable({ canDrop, onDrop }) is the layer under createListSortable. Register each item with sortable.useItem({ id, index, positions }), pass item.ref to its element, and spread item.attributes onto it. id, index, and the optional disabled and positions are accessors. positions can include inside for items that accept children.

onDrop and canDrop receive { sourceId, sourceIndex, targetId, targetIndex, position }. canDrop rejects a location before it shows an indicator. onDrop runs once per accepted drop; return the id the source has after the move when it differs from sourceId, so the drop animation finds its element.

import { For } from 'solid-js'
import { createSortable } from 'moraine/dnd'

const sortable = createSortable({
  onDrop: (drop) => console.log(drop.sourceId, drop.position, drop.targetId),
})

<sortable.Provider>
  <For each={['a', 'b', 'c']}>
    {(id, index) => {
      const item = sortable.useItem({ id: () => id, index })
      return (
        <li ref={item.ref} {...item.attributes}>
          {id}
        </li>
      )
    }}
  </For>
</sortable.Provider>

## Common pitfalls

- Update the items in `onReorder`. The sortable does not reorder them itself.
- Spread `row.props` on the outer row element, not an inner one, so the drop target covers the
  whole row and virtual row measurement keeps working.
- Call `useRow`, `useNode`, and `useItem` under `sortable.Provider`. On the client they throw
  outside it.
- The server renders rows without drag behavior; rows become draggable after hydration.