Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - setDragImage on draggable element

I'm trying to swap out the default image that the browser uses when I drag a draggable element (in this case the ul below). Here is my code. I'm not getting any errors - it just doesn't work, and I'm left with the default image used by the browser.

drag(e) {
  let img = new Image()
  img.src = 'https://some-image.png'
  e.dataTransfer.setDragImage(img, 0, 0)
}

render() {
  return(
    <ul draggable="true" onDrag={(e) => {this.drag(e)}>
      <li>1</li>
      <li>2</li>
    </ul>
  )
}
like image 407
Ben Avatar asked Jul 12 '17 08:07

Ben


1 Answers

The image is not yet loaded when you call setDragImage(). I handled this by creating the image on mount and storing it in state:

 componentDidMount() {
    const img = new Image();
    img.src = 'https://some-image.png';
    img.onload = () => this.setState({ dragImg: img });
 }
 drag(e) {
    e.dataTransfer.setDragImage(this.state.dragImg, 0, 0);
 }
like image 102
Sauce Avatar answered Oct 08 '22 22:10

Sauce