I am trying to create a drag and drop upload div. I am following a reference link that demonstrated removeEventListener in a class component unmounting phase.
Why can't I remove the event listener on unmounting phase with functional components? It seems like the ide is also not recognizing the removeEventListener
function. What did I do wrong?
Do I actually have to removeEventListener, as it seems like the component did not unmount in the whole lifecycle?
const dropRef = useRef(null);
const handleDrag = (e) => {
console.log("Drag Over detected!");
};
const handleDrop = (e) => {
console.log("Drop detected!");
};
useEffect(() => {
const div = dropRef.current;
div.addEventListener("dragover", handleDrag);
div.addEventListener("drop", handleDrop);
return () => {
div.removeEventListener("dragover", handleDrag);
div.removeEventListener("drop", handleDrop);
};
}, []);
<div className="uploadBox" ref={dropRef}></div>
CodePudding user response:
The Effect Hook lets you perform side effects in function components:
you are not passing any dependency to useEffect
which means, your useEffect
only runs once (at the time of page render).
You to run it, you need to define the dependencies when this useEffect
run,
in your case, passing div as a dependency should work.
useEffect(() => {
const div = dropRef.current;
div.addEventListener("dragover", handleDrag);
div.addEventListener("drop", handleDrop);
return () => {
div.removeEventListener("dragover", handleDrag);
div.removeEventListener("drop", handleDrop);
};
}, [div]);
CodePudding user response:
// Declare a static listener.
const eventListeners = useRef();
// now let's create our scroll Handler
const scrollHandler = useCallback(() => {...},[]);
useEffect(() => {
// Here will be removing the static listener and then updated it for
// our new one since the first time will be empty it won't do anything.
window.removeEventListener('scroll', eventListeners.current, true);
// Then will set our current scroll handler to our static listener
eventListeners.current = scrollHandler;
// Here will be adding the static listener so we can keep the reference
// and remove it later on
window.addEventListener('scroll', eventListeners.current, true);
},[scrollHandler]);