From 45a7694e640a02c0c7cce668194524ea0a2c743f Mon Sep 17 00:00:00 2001 From: Nikolay <46225163+vigdorov@users.noreply.github.com> Date: Mon, 28 Dec 2020 14:21:40 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D1=85=D1=83=D0=BA=D0=B0=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20=D0=BE=D1=82=D0=BB=D0=B0=D0=B2=D0=BB=D0=B8=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B2=D0=BD=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=82=D0=B5=D0=B9=D0=BD?= =?UTF-8?q?=D0=B5=D1=80=D0=B0=20(#37)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .eslintrc.json | 2 +- src/core/hooks/useOutsideClick.ts | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/core/hooks/useOutsideClick.ts diff --git a/.eslintrc.json b/.eslintrc.json index d6a48e9..e533e06 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -39,7 +39,7 @@ "react-hooks/exhaustive-deps": [ "warn", { - "additionalHooks": "(useTypedQuery|useTypedParams)" + "additionalHooks": "(useEqualMemo)" } ], "jsx-a11y/label-has-associated-control": 0, diff --git a/src/core/hooks/useOutsideClick.ts b/src/core/hooks/useOutsideClick.ts new file mode 100644 index 0000000..b5f3117 --- /dev/null +++ b/src/core/hooks/useOutsideClick.ts @@ -0,0 +1,25 @@ +import {useCallback, useEffect, useRef} from 'react'; + +export const useOutsideClick = (callback: EventListener) => { + const container = useRef(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; +};