Created
December 17, 2021 13:18
-
-
Save ChaseH88/b4d2486a8b0c68d7d8b8753c503b0c80 to your computer and use it in GitHub Desktop.
Hook to check if an element is clicked or not clicked.
This file contains 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 { useRef, useCallback, useEffect, MutableRefObject } from 'react'; | |
/** | |
* Hook to check if an element is clicked or not clicked. | |
* When the element isn't clicked, a callback function is fired. | |
* | |
* @param ref Ref element to listen to | |
* @param handler Call function that fires when element is outside click area | |
*/ | |
const useClickOutside = (ref: MutableRefObject<HTMLElement | null>, handler: (e: MouseEvent) => any): void => { | |
const currentHandler = useRef(handler); | |
const memoizedCallback = useCallback((e: MouseEvent) => { | |
if ( | |
ref && ref.current && | |
!ref.current.contains(e.target as Element) | |
) { | |
currentHandler.current(e); | |
} | |
}, []); | |
useEffect(() => { | |
currentHandler.current = handler; | |
}); | |
useEffect(() => { | |
document.addEventListener("click", memoizedCallback, true); | |
return () => { | |
document.removeEventListener("click", memoizedCallback, true); | |
}; | |
}, [ref, handler]); | |
} | |
export { useClickOutside }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment