Skip to content

Commit

Permalink
- implemented hook useClickOutside
Browse files Browse the repository at this point in the history
- created ref wrapperRef to handle click out side dropdown
  • Loading branch information
Konstantin Zharich committed Feb 24, 2023
1 parent 13abc54 commit 4bc2702
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
19 changes: 19 additions & 0 deletions packages/ketcher-react/src/hooks/useClickOutside.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect, RefObject } from 'react'

export const useClickOutside = (
targetRef: RefObject<Node>,
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()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand All @@ -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<HTMLDivElement>(null)
const onClickOutsideCloseDrowndown = (): void =>
setIsShowingFontSizeMenu(false)
useClickOutside(wrapperRef, onClickOutsideCloseDrowndown)

const setFontSize = (e, value) => {
e.preventDefault()
Expand Down Expand Up @@ -58,7 +63,7 @@ export const FontControl = ({ editorState, setEditorState, styles }) => {
)

return (
<div>
<div ref={wrapperRef}>
<button
className={classes.fontBtn}
onMouseDown={(e) => {
Expand Down

0 comments on commit 4bc2702

Please sign in to comment.