Skip to content

Instantly share code, notes, and snippets.

@paulohfev
Last active March 12, 2024 11:27
Show Gist options
  • Save paulohfev/f0cf9ef7258f182861b40105c4ee7213 to your computer and use it in GitHub Desktop.
Save paulohfev/f0cf9ef7258f182861b40105c4ee7213 to your computer and use it in GitHub Desktop.
useOutsideClick React Hook w/ TypeScript
import { useEffect } from 'react';
export const useOutsideClick = (callback: (T?: any) => void, ref: React.RefObject<HTMLDivElement>) => {
const handleClick = (e: Event) => {
if (ref.current && !ref.current.contains(<HTMLElement>e.target)) {
callback();
}
};
useEffect(() => {
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};
});
};
@perepalacin
Copy link

Greetings! Thanks a lot for your code snippet! Nevertheless, I was having some troubles using the type for the e.target argument. I instead used e.target as HTMLElement and it worked, any ideas why is that? Thanks!!

export const useOutsideClick2 = (callback: (T?: any) => void, ref: React.RefObject<HTMLDivElement>) => {
  const handleClick = (e: Event) => {
    if (ref.current && !ref.current.contains(e.target as HTMLElement)) {
      callback();
    }
  };

  useEffect(() => {
    document.addEventListener('click', handleClick);

    return () => {
      document.removeEventListener('click', handleClick);
    };
  });
};

@paulohfev
Copy link
Author

Greetings. Most likely there was a typing conflict with the JSX syntax steeming from the original example. <HTMLElement>e.target and e.target as HTMLElement achieve the same goal, so there shouldn't be an issue! Thanks for pointing it out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment