From d5e8164a24d7bb250527c0c513ae2b4e41d47331 Mon Sep 17 00:00:00 2001 From: Jitendra Nirnejak Date: Sat, 16 Nov 2024 18:20:46 +0530 Subject: [PATCH] useClickOutside: returning ref --- hooks/useClickOutside.tsx | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/hooks/useClickOutside.tsx b/hooks/useClickOutside.tsx index 641d3d8..455f3e2 100644 --- a/hooks/useClickOutside.tsx +++ b/hooks/useClickOutside.tsx @@ -1,21 +1,32 @@ import * as React from "react" -const useClickOutside = (ref, handler) => { +type Event = MouseEvent | TouchEvent + +const useClickOutside = ( + handler: (event: Event) => void +): React.RefObject => { + const ref = React.useRef(null) + React.useEffect(() => { - const listener = (event) => { - if (!ref.current || ref.current.contains(event.target)) { + const listener = (event: Event): void => { + const el = ref?.current + if (el == null || el.contains(event?.target as Node)) { return } - handler(event) + handler(event) // Call the handler only if the click is outside of the element passed. } - document.addEventListener("click", listener) + document.addEventListener("mousedown", listener) + document.addEventListener("touchstart", listener) return () => { - document.removeEventListener("click", listener) + document.removeEventListener("mousedown", listener) + document.removeEventListener("touchstart", listener) } - }, [ref, handler]) + }, [ref, handler]) // Reload only if ref or handler changes + + return ref } export default useClickOutside