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

34 lines
836 B

import { useRef } from 'react'
import { useEventListener } from 'hooks'
type Args = {
onClick: (event?: MouseEvent) => void,
}
export const useOutsideClickEffect = ({
onClick,
}: Args) => {
const wrapperRef = useRef<HTMLDivElement>(null)
const handleOutsideClick = (e: MouseEvent) => {
const targetNode = e.target instanceof Node
? e.target
: null
/** деструктуризация wrapperRef не сработает, ссылка на реф теряется */
if (!wrapperRef.current?.contains(targetNode)) {
onClick(e)
}
}
const onKeyPress = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClick()
}
}
useEventListener({ callback: handleOutsideClick, event: 'click' })
useEventListener({ callback: onKeyPress, event: 'keydown' })
return wrapperRef
}