How to Attach Drag & Drop Event Listeners to a React component
You don't need to use props. You can just add all the events inside your DropZone component.
http://codepen.io/jzmmm/pen/bZjzxN?editors=0011
This is where i add the events:
componentDidMount() {
window.addEventListener('mouseup', this._onDragLeave);
window.addEventListener('dragenter', this._onDragEnter);
window.addEventListener('dragover', this._onDragOver);
window.addEventListener('drop', this._onDrop);
document.getElementById('dragbox').addEventListener('dragleave', this._onDragLeave);
}
Your render method:
render() {
return (
<div>
{this.props.children}
<div id="dragbox" className={this.state.className}>
Drop a file to Upload
</div>
</div>
);
}
As you can see in componentDidMount, i added an eventlistener to #dragbox as well. Because once you drag a file over the page, #dragbox is under the mouse cursor, so it needs a dragleave in case you decide you don't want to drop the file there.
Also, dragover
is needed to capture the drop
Then in my App component, i can use it like this:
class App extends React.Component {
render() {
return (
<DropZone>
<div>
<h1>Drag A File Here...</h1>
</div>
</DropZone>
);
}
}