Ad

How To Remove A Event Listener In The Context Of Dragging A React Component

The mousemove does not appear to be properly removed from document when releasing the mouse.

https://codesandbox.io/s/dragondrop-dqs46

Ad

Answer

Rather than manually adding and removing when relevant, write a custom hook useEvent that will store handlers from one render to another:

useEvent.js

import { useEffect, useRef } from "react";

export default function(event, handler, element=window) {

  const savedHandler = useRef();

  useEffect(() => {
    savedHandler.current = handler;
  }, [handler]);

  useEffect(() => {
    const eventListener = event => savedHandler.current(event);
    element.addEventListener(event, eventListener);
    return () => element.removeEventListener(event, eventListener);
  }, [event, element]);
}

components/Dragon.js

useEvent("mousemove", onDrag);
useEvent("mouseup", onDragEnd);

Working pen: https://codesandbox.io/s/dragondrop-ceocx

Ad
source: stackoverflow.com
Ad