Skip to content

Instantly share code, notes, and snippets.

@ChaseH88
Created December 17, 2021 13:18
Show Gist options
  • Save ChaseH88/b4d2486a8b0c68d7d8b8753c503b0c80 to your computer and use it in GitHub Desktop.
Save ChaseH88/b4d2486a8b0c68d7d8b8753c503b0c80 to your computer and use it in GitHub Desktop.
Hook to check if an element is clicked or not clicked.
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