Skip to content

Instantly share code, notes, and snippets.

@LeeCheneler
Created May 26, 2022 18:37
Show Gist options
  • Save LeeCheneler/1fa695bddf24cb2a3492c7fecf5c6550 to your computer and use it in GitHub Desktop.
Save LeeCheneler/1fa695bddf24cb2a3492c7fecf5c6550 to your computer and use it in GitHub Desktop.
use-outside-click
import React from "react";
export const useOutsideClick = (
refs: React.MutableRefObject<any>[],
callback: () => void
) => {
React.useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (
refs.every(
(ref) =>
ref.current &&
!ref.current.contains(e.target as Node) &&
ref.current !== e.target
)
) {
callback();
}
};
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
}, [refs, callback]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment