Skip to content

Instantly share code, notes, and snippets.

@freddi301
Last active July 25, 2023 17:20
Show Gist options
  • Save freddi301/21e04fb53b046ceb300620034b56d081 to your computer and use it in GitHub Desktop.
Save freddi301/21e04fb53b046ceb300620034b56d081 to your computer and use it in GitHub Desktop.
react hook that notifies when clicking outside an element
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