diff --git a/src/components/utils/useOnClickOutside/index.ts b/src/components/utils/useOnClickOutside/index.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/components/utils/useOnClickOutside/useOnClickOutside.tsx b/src/components/utils/useOnClickOutside/useOnClickOutside.tsx new file mode 100644 index 0000000000..e3be395fcb --- /dev/null +++ b/src/components/utils/useOnClickOutside/useOnClickOutside.tsx @@ -0,0 +1,36 @@ +import React from 'react'; + +export type UseOnClickOutsideType = ({ + observedRef, + enabled, +}: { + observedRef: React.RefObject; + enabled?: boolean; + handleCallback?: () => void; +}) => void; + +export const useOnClickOutside: UseOnClickOutsideType = ({ + observedRef, + enabled = true, + handleCallback, +}) => { + React.useEffect(() => { + if (enabled && observedRef) { + const handler = (e: MouseEvent) => { + const elem = observedRef?.current; + + if (elem && !elem.contains(e.target as Node) && handleCallback) { + handleCallback(); + } + }; + + window.addEventListener('click', handler, {capture: true}); + + return () => { + window.removeEventListener('click', handler, {capture: true}); + }; + } + + return undefined; + }, [enabled, handleCallback, observedRef]); +};