From 4bc270237e4a3e85640ada481808d70b9379bb30 Mon Sep 17 00:00:00 2001 From: Konstantin Zharich Date: Fri, 24 Feb 2023 14:33:54 +0100 Subject: [PATCH] - implemented hook useClickOutside - created ref wrapperRef to handle click out side dropdown --- .../src/hooks/useClickOutside.ts | 19 +++++++++++++++++++ .../Text/FontControl/FontControl.tsx | 9 +++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 packages/ketcher-react/src/hooks/useClickOutside.ts diff --git a/packages/ketcher-react/src/hooks/useClickOutside.ts b/packages/ketcher-react/src/hooks/useClickOutside.ts new file mode 100644 index 0000000000..a82fa87606 --- /dev/null +++ b/packages/ketcher-react/src/hooks/useClickOutside.ts @@ -0,0 +1,19 @@ +import { useEffect, RefObject } from 'react' + +export const useClickOutside = ( + targetRef: RefObject, + callback: () => void +): void => { + useEffect(() => { + document.addEventListener('click', onClickOutside) + return () => { + document.removeEventListener('click', onClickOutside) + } + }, []) + + const onClickOutside = (e: Event) => { + if (!targetRef.current?.contains(e.target as Node)) { + callback() + } + } +} diff --git a/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx b/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx index b75ee85f59..10c8c40ce5 100644 --- a/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx +++ b/packages/ketcher-react/src/script/ui/views/modal/components/Text/FontControl/FontControl.tsx @@ -14,7 +14,8 @@ * limitations under the License. ***************************************************************************/ -import { useEffect, useMemo, useState } from 'react' +import { useEffect, useMemo, useState, useRef } from 'react' +import { useClickOutside } from '../../../../../../../hooks/useClickOutside' import classes from './FontControl.module.less' @@ -24,6 +25,10 @@ export const FontControl = ({ editorState, setEditorState, styles }) => { const defaultFontSize = '13px' const [isShowingFontSizeMenu, setIsShowingFontSizeMenu] = useState(false) const [currentFontSize, setCurrentFontSize] = useState(defaultFontSize) + const wrapperRef = useRef(null) + const onClickOutsideCloseDrowndown = (): void => + setIsShowingFontSizeMenu(false) + useClickOutside(wrapperRef, onClickOutsideCloseDrowndown) const setFontSize = (e, value) => { e.preventDefault() @@ -58,7 +63,7 @@ export const FontControl = ({ editorState, setEditorState, styles }) => { ) return ( -
+