Skip to content

Instantly share code, notes, and snippets.

@ruvasik
Created January 17, 2023 14:26
Show Gist options
  • Save ruvasik/20f80462e353cc57dfc8f9740bd5240c to your computer and use it in GitHub Desktop.
Save ruvasik/20f80462e353cc57dfc8f9740bd5240c to your computer and use it in GitHub Desktop.
React typed hook useOnClickOutside
import React from "react";
export default function useOnClickOutside(
ref: React.RefObject<HTMLElement>,
handler: (event: TouchEvent | MouseEvent) => void
) {
React.useEffect(() => {
const listener = (event: TouchEvent | MouseEvent) => {
if (!ref.current || ref.current.contains(event.target as HTMLElement)) {
return;
}
handler(event);
};
document.addEventListener("mousedown", listener);
document.addEventListener("touchstart", listener);
return () => {
document.removeEventListener("mousedown", listener);
document.removeEventListener("touchstart", listener);
};
}, [ref, handler]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment