Last active
July 25, 2023 17:20
-
-
Save freddi301/21e04fb53b046ceb300620034b56d081 to your computer and use it in GitHub Desktop.
react hook that notifies when clicking outside an element
This file contains hidden or 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 React from "react"; | |
export function useClickAway<E extends HTMLElement | null>( | |
ref: React.MutableRefObject<E>, | |
onClickAway: () => void | |
) { | |
const wasInsideRef = React.useRef(false); | |
React.useLayoutEffect(() => { | |
const onClick = (event: MouseEvent) => { | |
if (ref.current?.contains(event.target as Node)) { | |
wasInsideRef.current = true; | |
} else { | |
if (wasInsideRef.current) { | |
onClickAway(); | |
} | |
wasInsideRef.current = false; | |
} | |
}; | |
document.addEventListener("click", onClick); | |
return () => document.addEventListener("click", onClick); | |
}, [ref, onClickAway]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment