You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
27 lines
655 B
27 lines
655 B
import { useRef } from 'react'
|
|
|
|
import { useEventListener } from 'hooks'
|
|
|
|
type Args = {
|
|
onClick: Function,
|
|
}
|
|
|
|
export const useOutsideClickEffect = ({
|
|
onClick,
|
|
}: Args) => {
|
|
const wrapperRef = useRef<HTMLDivElement>(null)
|
|
const handleOutsideClick = ({ target }: MouseEvent) => {
|
|
const targetNode = target instanceof Node
|
|
? target
|
|
: null
|
|
|
|
/** деструктуризация wrapperRef не сработает, ссылка на реф теряется */
|
|
if (!wrapperRef.current?.contains(targetNode)) {
|
|
onClick()
|
|
}
|
|
}
|
|
|
|
useEventListener({ callback: handleOutsideClick, event: 'click' })
|
|
|
|
return wrapperRef
|
|
}
|
|
|