diff --git a/src/hooks/useOutsideClickEventHandler.ts b/src/hooks/useOutsideClickEventHandler.ts new file mode 100644 index 0000000..0ac43e9 --- /dev/null +++ b/src/hooks/useOutsideClickEventHandler.ts @@ -0,0 +1,30 @@ +import type { RefObject } from 'react' +import { useEffect, useRef } from 'react' + +export const useOutSideClickEventHandler = (callback: () => void): RefObject => { + const wrapper = useRef(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 +}