Search code examples
reactjsreact-dnd

React DND - Use different name prop for each compoents


I'm trying one of react-dnd code examples: https://github.com/react-dnd/react-dnd/blob/master/examples/01%20Dustbin/Single%20Target/Dustbin.js

const boxTarget = {
  drop() {
    return { name: 'Dustbin' }
  }
}

@DropTarget(ItemTypes.BOX, boxTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop(),
}))

export default class Dustbin extends Component {
  ...
}

On the example, the name is hard coded. I need to use dynamic name so I passed a prop like this one

<Dustbin name="dustbin1" />
<Dustbin name="dustbin2" />

and changed the boxTarget into

const boxTarget = {
  drop() {
    return { name: this.props.name }
  }
}

However this.props became undefined, maybe because it's not inside the class. Is there any workaround so I can use different name for each Dustbin components?


Solution

  • The drop function gets passed the props, but has no access to this (see http://react-dnd.github.io/react-dnd/docs-drop-target.html), so you just need to rewrite the boxTarget to look like:

    const boxTarget = {
      drop(props) {
        return { name: props.name }
      }
    }
    

    And it will be able to return the name that you passed to it as a prop