Prabodh M
Prabodh M

Reputation: 2262

Unable to get onDragStart Event on React for HTML5 Drag and Drop

I am creating a basic application in ReactJs to implement the basic HTML5 Drag and Drop functionality. The issue I am facing is, my onDragStart event is not passing the event object to the handler method. I have referred the documentation of HTML5 Drag and Drop, where it has shown how event object is passed to handler.

This is my code to implement the event Handler for onDragStart event.

//handler method
dragStartHandler(event) {
 console.log(event); // undefined
}

render() {
 return (
   <div draggable="true" 
    onDragStart={this.dragStartHandler(event)}></div>
 )
}

The handler is getting called but without the event object. My agenda is to capture the event object so that I can proceed further to bind data to the event, using the DataTransfer interface.

Please help me understand the behavior.

Thanks!

Update

Not passing the event to the dragStartHandler method actually passes the event to the handler method. Its just the way react works to bind a method, unlike what is mentioned in the HTML5 DND documentation, seem not to work with react. The event which I got in the handler was wrapped up version of original Drag Event as per html specs. This behavior just confused me as it was giving some Proxy object might be created by react.

Solution : Although the Proxy object has all the methods of original Drag event, I realized it later. So you can use the new Proxy event object as you did previously as native html element, with all previous behavior.

Upvotes: 7

Views: 32549

Answers (1)

Mikhail Shabrikov
Mikhail Shabrikov

Reputation: 8509

Replace

onDragStart={this.dragStartHandler(event)}

to

onDragStart={this.dragStartHandler}

You should pass a function to onDragStart property, (as for any other events-related property like onClick, onMouseEnter etc.), not result of the function invocation as you did. React.js will pass the event object as an argument to the handler function "under the hood". However, you must remember, that React.js creates a wrapper around native JavaScript event. Its name "SyntheticEvent". See docs for details. But, you can get access to a native event in the handler function (see the code below):

var Draggable = React.createClass({
    handleDrag(event) {
    console.log('react SyntheticEvent ==> ', event);
    console.log('nativeEvent ==> ', event.nativeEvent); //<- gets native JS event
  },

  render: function() {
    return (<div draggable="true" onDragStart={this.handleDrag}>
                Open console and drag me!
            </div>);
  }
});

ReactDOM.render(
  <Draggable />,
  document.getElementById('container')
);

Look at this example in action - https://jsfiddle.net/yrhvw0L0/2/

Upvotes: 10

Related Questions