Created
December 21, 2024 07:52
-
-
Save himanshupal/15e529bc23c62646111c0f52258e6d7d to your computer and use it in GitHub Desktop.
React hook to do some action on click away from given element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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