diff options
| author | Armand Philippot <git@armandphilippot.com> | 2023-11-01 16:10:31 +0100 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2023-11-11 18:15:27 +0100 |
| commit | 1e4b48aa075e6131a7244cd4726ddb5ba75fcecf (patch) | |
| tree | ba0377440419f6690f079c1fc9de5915db805a38 /src/utils/hooks/use-on-click-outside.tsx | |
| parent | 2844a2bd71dcf1eb17a53992c10129b7496332e0 (diff) | |
refactor(hooks): rewrite useOnClickOutside hook
* remove `useCapture` parameter (it does not make sense to use bubbling
here)
* return a MutableRefObject instead of a RefObject to be able to test
the hook
Diffstat (limited to 'src/utils/hooks/use-on-click-outside.tsx')
| -rw-r--r-- | src/utils/hooks/use-on-click-outside.tsx | 50 |
1 files changed, 0 insertions, 50 deletions
diff --git a/src/utils/hooks/use-on-click-outside.tsx b/src/utils/hooks/use-on-click-outside.tsx deleted file mode 100644 index b810ddc..0000000 --- a/src/utils/hooks/use-on-click-outside.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { RefObject, useCallback, useEffect, useRef } from 'react'; - -export type UseOnClickOutsideCallback = (target: Node) => void; - -/** - * Detect click/focus outside an element and fire a callback function. - * - * @param {UseOnClickOutsideCallback} callback - A callback function to fire. - * @param {boolean} useCapture - Define event propagation method. Default: true. - * @returns {RefObject} A React reference object. - */ -export const useOnClickOutside = <T extends HTMLElement>( - callback: UseOnClickOutsideCallback, - useCapture: boolean = true -): RefObject<T> => { - const ref = useRef<T | null>(null); - - /** - * Check if the target is outside the ref. - * - * @param {Node} target - The event target. - * @returns {boolean | null} True if the target is outside the ref. - */ - const isTargetOutside = (target: Node): boolean | null => { - return ref.current && !ref.current.contains(target); - }; - - /** - * Fire the callback if the event target is outside. - */ - const handler = useCallback( - (e: MouseEvent | FocusEvent) => { - if (e.target && isTargetOutside(e.target as Node)) - callback(e.target as Node); - }, - [callback] - ); - - useEffect(() => { - document.addEventListener('click', handler, useCapture); - document.addEventListener('focusin', handler, useCapture); - - return () => { - document.removeEventListener('click', handler); - document.removeEventListener('focusin', handler); - }; - }, [handler, useCapture]); - - return ref; -}; |
