Example is a functional component. I am using useRef()
hook to get the ref a div element. I want to attach an event listener to the ref when Example mounts.
const Example: React.FC = () => {
const ref = useRef<HTMLDivElement>(null);
const handleClick = (): void => {
// mouse click logic
};
useEffect(() => {
if (ref && ref.current) {
ref.current.addEventListener('click', handleClick);
}
return (): void => {
if (ref && ref.current) {
ref.current.removeEventListener('click', handleClick);
}
};
}, []);
return (
<div ref={ref} />
);
};
What's happening is that the ref is still null when Example did mount. So, I am unable to attach event listener
to it. An alternative solution would be to assign an id
to div and attach event listener to the DOM node directly which I don't really want to do.
Any guidance on how can I attach event listener to the ref will be really helpful :)