Skip to content

Instantly share code, notes, and snippets.

@anpct
Last active November 3, 2021 19:04
Show Gist options
  • Save anpct/556ca146c7acdff05e622585c9e36f03 to your computer and use it in GitHub Desktop.
Save anpct/556ca146c7acdff05e622585c9e36f03 to your computer and use it in GitHub Desktop.
useListener
import { useEffect, useRef } from "react";
const useListener = (outsideFunction) => {
const ref = useRef();
useEffect(() => {
const handleClick = (event) => {
if (ref.current && ref.current.contains(event.target)) {
return;
}
outsideFunction();
};
document.addEventListener("mousedown", handleClick);
return () => {
document.removeEventListener("mousedown", handleClick);
};
}, [outsideFunction]);
return ref;
};
export default useListener;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment