Search code examples
reactjsreact-dnd

React-Dnd: Dynamic DropTarget and DragSource type


I'm building a multi-level nestable drag and drop list. Each nested list needs to allow dragging only within itself. This requires setting a run-time type for the DragSource and DropTarget.

Compile time type declaration works but is limited

export default flow(
  DropTarget(ItemLevel.ROOT, target, connect => ({
    connectDropTarget: connect.dropTarget(),
  })),
  DragSource(ItemLevel.ROOT, source, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
  })),
)(MenuItem)

Runtime type declaration seems to work but throws errors on dragging

export const getGroupMenuItem = menuGroupId => flow(
  DropTarget(menuGroupId, target, connect => ({
    connectDropTarget: connect.dropTarget(),
  })),
  DragSource(menuGroupId, source, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
  })),
)(MenuItem)

enter image description here


Solution

  • According to react-dnd document, the type could be a function which is given component's props. This drop target will only react to the items produced by the drag sources of the specified type or types.