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

I am creating a basic application in ReactJs to implement basic HTML5 drag and drop functionality. The problem I am facing is this event onDragStart

does not pass the event object to the handler method. I referenced the HTML5 drag and drop documentation where it showed how an event object is passed to a handler.

This is my code for implementing an event handler for an event onDragStart

.

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

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

      

The handler gets called, but no event object. My task is to grab the event object so that I can continue further data binding to the event using the DataTransfer interface.

Please help me understand the behavior.

Thank!

Update

Don't pass event to method dragStartHandler

actually passes the event to the handler method. Its just a way to be responsive to method binding, unlike what is mentioned in the HTML5 DND doc documentation doesn't seem to work with responsiveness. The event I received in the handler completed the version of the original Drag Event as per the html specs. This behavior just confused me as it gave some Proxy object that could be created by reacting.

Solution . Although the Proxy object has all the methods of the original Drag event, I figured it out later. This way you can use the new Proxy event as you did earlier as a custom html element, with all the previous behavior.

+3


source to share


1 answer


Replace

onDragStart={this.dragStartHandler(event)}

to

onDragStart={this.dragStartHandler}



You should pass the function to the property onDragStart

(as for any other event-related property, such as onClick

, onMouseEnter

etc.), not the result of the function call, as you did. React.js will pass the event object as an argument to the under the hood handler function. However, you should remember that React.js wraps its own JavaScript event. Its name is "SyntheticEvent". See the docs for details . But you can access your own event in the handler function (see 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')
);

      

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

+3


source







All Articles