feat(hooks): implement useOutsideClickEventHandler
This commit is contained in:
parent
052ad1c6ab
commit
1919787c11
30
src/hooks/useOutsideClickEventHandler.ts
Normal file
30
src/hooks/useOutsideClickEventHandler.ts
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import type { RefObject } from 'react'
|
||||||
|
import { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
export const useOutSideClickEventHandler = (callback: () => void): RefObject<HTMLDivElement> => {
|
||||||
|
const wrapper = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (event: KeyboardEvent): void => {
|
||||||
|
if (Boolean(wrapper.current?.contains(event.target as Node))) return
|
||||||
|
if (event.key !== 'Escape') return
|
||||||
|
return callback()
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('click', (event: any) => {
|
||||||
|
return handleClickOutside(event)
|
||||||
|
})
|
||||||
|
|
||||||
|
window.addEventListener('keydown', (event: any) => {
|
||||||
|
return handleClickOutside(event)
|
||||||
|
})
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
return window.removeEventListener('click', (event: any) => {
|
||||||
|
return handleClickOutside(event)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user