Search code examples
reactjsreact-dnd

React dnd to push object of dropped item to component's state.


In my component, there are local state of paid and droppedItems.

constructor () {
 super();
 this.state = {
  droppedItems: [],
};

And I specified drop specification like below,

drop(props, monitor) { const orderItem = monitor.getItem(); },

What I want to do is that when an orderItem is dropped to the target, it pushes orderItem to state of droppedItems So to do that, I made handleDrop function

handleDrop (orderItem) {
 if(!orderItem){
     this.setState(update(this.state, {
  droppedItems: orderItem ? {
    $push: [orderItem]
  } : {}
}));
}
else return false;
}

And call it like this

return connectDropTarget(
            <div className="payment_block" onDrop={this.handleDrop}>

In my render function, there are const { canDrop, connectDropTarget, getItem} = this.props;

Below is result from console.log(this.props)

Object { id: 1, order: Object, channel: undefined, dispatch: routerMiddleware/</</<(), connectDropTarget: wrapHookToRecognizeElement/<(), canDrop: false, itemType: "order_item", getItem: Object

Although it recognizes that there is a dropped item, it does not push to the state.

How can I push above Object of getItem to the component's state? What am I doing wrong here?

Thanks in advance


Solution

  • The signature of drop also receives your dnd decorated component as its third argument, so you should be able to call your handleAdd method.

    drop(props, monitor, component) {
      component.handleDrop(monitor.getItem());
    }
    

    Also the if statement in your handleDrop method is checking that no orderItem is passed in, which means the code will never run when you want it to, I'm not familiar with the what your update function does (presumably immutably pushing to the array), but perhaps something like this would work...

    handleDrop: function(orderItem) {
      if (!!orderItem) {
        this.setState(
          update(this.state, { droppedItems: { $push: [orderItem] } })
        )
      }
    }