Добавление хука для отлавливания кликов вне контейнера (#37)
This commit is contained in:
@ -39,7 +39,7 @@
|
|||||||
"react-hooks/exhaustive-deps": [
|
"react-hooks/exhaustive-deps": [
|
||||||
"warn",
|
"warn",
|
||||||
{
|
{
|
||||||
"additionalHooks": "(useTypedQuery|useTypedParams)"
|
"additionalHooks": "(useEqualMemo)"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"jsx-a11y/label-has-associated-control": 0,
|
"jsx-a11y/label-has-associated-control": 0,
|
||||||
|
|||||||
25
src/core/hooks/useOutsideClick.ts
Normal file
25
src/core/hooks/useOutsideClick.ts
Normal 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;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user