Last active
March 12, 2024 11:27
-
-
Save paulohfev/f0cf9ef7258f182861b40105c4ee7213 to your computer and use it in GitHub Desktop.
useOutsideClick React Hook w/ TypeScript
This file contains 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 { 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); | |
}; | |
}); | |
}; |
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
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!!