import React, {useEffect} from 'react';
export function useOutsideClickEventHandler <T extends HTMLElement = HTMLElement> (ref: React.RefObject<T>, handler: (event: Event) => void): void {
useEffect(function (): () => void {
function handleClickOutside (event: Event): void {
if (ref.current && !ref.current.contains(event.target as Node)) {
handler(event);
}
}
document.addEventListener('mousedown', handleClickOutside);
return function (): void {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [ref, handler]);
}
const elementRef: React.MutableRefObject<HTMLDivElement> = useRef<HTMLDivElement>(null);
useOutsideClickEventHandler(elementRef, function (): void {
console.log('You clicked outside div.');
});
return <div ref={elementRef}>Try to click outside this div.</div>;
Комментариев нет:
Отправить комментарий