9

I am implementing a drag and drop effect in React.js. How do I use a custom React component or fragment (which doesn't necessarily exist yet in the DOM at the time the drag is initiated) as the drag image passed to setDragImage, rather than a static image of the dragged item?

For example:

onDragStart = (e, index) => {       
    this.draggedIndex = index;
    this.draggedItem = this.state.list[index];
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/html", e.target.parentNode);
    e.dataTransfer.setDragImage(??????);
};

The expected result is a custom preview component.

1 Answer 1

6

Was searching for the same thing until I finally stumbled upon the answer. Hope this helps someone (TSX):

private onDragStart(e: React.DragEvent) {
    let image: JSX.Element = (<></>); // <== whatever you want here

    var ghost = document.createElement('div');
    ghost.style.transform = "translate(-10000px, -10000px)";
    ghost.style.position = "absolute";
    document.body.appendChild(ghost);
    e.dataTransfer.setDragImage(ghost, 0, 0);

    ReactDOM.render(image, ghost); 
}

(This is a little over-simplified as you also need to remove the ghost from the DOM after a drop).

1
  • 2
    Been looking for this answer for like 20 hours. Thanks so much! Commented Apr 7, 2023 at 20:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.