React/Dnd: Make a component draggable and droppable at the same time

4.7k views Asked by At

There are multiple elements, which I want to get draggable and droppable at the same time - using react dnd. That means I need to drag one of the elements and drop it over another element.

First I defined the dragSource for MyComponent. That works so far. But how do I have to setup the DropTarget for the same component?

import React, { Component } from 'react'
import { DragSource, DropTarget } from 'react-dnd'

const elementSource = {
  beginDrag (props) {
    return { }
  }
}
const elementTarget = {
  drop (props, monitor) { }
}

function collect (connect, monitor) {
  return {
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver()
  }
}

class MyComponent extends Component {
  render () {
    const { connectDragSource, isDragging, connectDropTarget, isOver } = this.props

    return connectDragSource(
      <div style={{ opacity: isDragging ? 0.5 : 1 }} >
        Just an example
      </div>
    )
  }
}

export default DragSource('element', elementSource, collect)(MyComponent)
1

There are 1 answers

0
Shivam On

This is possible with React-DND. It requires exporting the draggable element both as Source and Target.

You could define the component as

class MyComponent extends Component {
  render () {
    const { connectDragSource, isDragging, connectDropTarget, isOver } = this.props

    return connectDragSource(connectDropTarget(
      <div style={{ opacity: isDragging ? 0.5 : 1 }} >
        Just an example
     </div>
    ))
  }
}

MyComponent = DragSource('MyComponent', elementSource, (connect, 
monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging()
}))(MyComponent);

MyComponent = DropTarget('MyComponent', elementTarget, connect => ({
  connectDropTarget: connect.dropTarget(),
}))(MyComponent);

export default MyComponent;

An example for the same is available here. It uses generators though.