Skip to content

Instantly share code, notes, and snippets.

@himanshupal
Created December 21, 2024 07:52
Show Gist options
  • Save himanshupal/15e529bc23c62646111c0f52258e6d7d to your computer and use it in GitHub Desktop.
Save himanshupal/15e529bc23c62646111c0f52258e6d7d to your computer and use it in GitHub Desktop.
React hook to do some action on click away from given element
import { useEffect, useRef } from "react";
const useClickAwayListener = <T extends HTMLElement = HTMLDivElement>(callback: VoidFunction) => {
const ref = useRef<T>(null);
useEffect(() => {
const handleClick = (event: MouseEvent) => {
const target = event.target as T;
if (event.target !== ref.current) {
if (target.contains(ref.current) && target !== ref.current) {
callback();
}
}
};
document.addEventListener("click", handleClick, { capture: true });
return () => {
document.removeEventListener("click", handleClick, { capture: true });
};
}, [callback]);
return ref;
};
export default useClickAwayListener;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment