Добавление хука для отлавливания кликов вне контейнера (#37)

This commit is contained in:
Nikolay
2020-12-28 14:21:40 +03:00
committed by GitHub
parent 9cb663aa65
commit 45a7694e64
2 changed files with 26 additions and 1 deletions

View File

@ -0,0 +1,25 @@
import {useCallback, useEffect, useRef} from 'react';
export const useOutsideClick = <T extends HTMLElement>(callback: EventListener) => {
const container = useRef<T>(null);
const handleEvent = useCallback((e: Event) => {
if (container.current && e.target !== null) {
if (!container.current.contains(e.target as Node)) {
callback(e);
}
}
}, [callback]);
useEffect(() => {
document.addEventListener('mousedown', handleEvent, true);
document.addEventListener('touchstart', handleEvent, true);
return () => {
document.removeEventListener('mousedown', handleEvent, true);
document.removeEventListener('touchstart', handleEvent, true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return container;
};