Ben
Ben

Reputation: 5432

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>
  )
}

Upvotes: 7

Views: 3526

Answers (1)

Sauce
Sauce

Reputation: 662

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);
 }

Upvotes: 3

Related Questions