I'm trying to trigger a drop-zone for files in my UI but only when you drag a file onto the window a la Google Images. However, the dragenter
and dragleave
seem to trigger on all children and not just the item I've added the listener to. I've tried preventDefault
and stopPropagation
but neither helps.
I'm trying to avoid running a parent check on every event trigger since I need it to turn off when you leave the window as well and I'm not sure if it'll work with that since technically the leave still has a parent of inside the window?
My simplified code is as follows:
const [dragging, setDragging] = useState(false);
const dragEnter = event => {
event.preventDefault();
event.stopPropagation();
setDragging(true);
};
const dragLeave = event => {
event.preventDefault();
event.stopPropagation();
setDragging(false);
};
useEffect(() => {
window.addEventListener("dragenter", dragEnter, false);
window.addEventListener("dragleave", dragLeave, false);
return () => {
window.removeEventListener("dragenter", dragEnter, false);
window.removeEventListener("dragleave", dragLeave, false);
};
}, []);
Here's a really simplified demo of it "working". I feel like this has got to be a solved problem but I'm not having a lot of luck Googling it.
This is all going to live inside a React project, though I don't think that's what's getting me here.