feat(hooks): implement useOutsideClickEventHandler

This commit is contained in:
Walid 2023-04-23 20:16:56 +01:00
parent 052ad1c6ab
commit 1919787c11
Signed by: Walidoux
GPG Key ID: CCF21881FE8BEBAF

View 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
}