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.
 
 
 
 
spa_instat_tv/src/features/OutsideClick/hooks/index.tsx

30 lines
801 B

import { useEffect, useRef } from 'react'
type TUseOutsideClickEffect = {
onClick: Function,
}
export const useOutsideClickEffect = ({
onClick,
}: TUseOutsideClickEffect) => {
const wrapperRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleOutsideClick = ({ target }: MouseEvent) => {
const targetNode = target instanceof Node
? target
: null
/** деструктуризация wrapperRef не сработает, ссылка на реф теряется */
if (!wrapperRef.current?.contains(targetNode)) {
onClick()
}
}
window.addEventListener('click', handleOutsideClick)
return () => {
window.removeEventListener('click', handleOutsideClick)
}
}, [onClick, wrapperRef])
return wrapperRef
}