Last active
June 22, 2022 04:57
-
-
Save fronterior/faa559cb9be050959f3cc333c0053595 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, RefObject } from 'react'; | |
const useOutsideClick = <T extends HTMLElement>(f: (ev: MouseEvent) => void, ref: RefObject<T>) => { | |
useEffect(() => { | |
const upHandler = (ev: MouseEvent) => { | |
ev.stopPropagation(); | |
document.removeEventListener('click', upHandler, true); | |
f(ev); | |
}; | |
const downHandler = (ev: PointerEvent) => { | |
if (ref?.current && !ref?.current.contains(ev.target as HTMLElement)) { | |
document.addEventListener('click', upHandler, true); | |
} | |
}; | |
document.addEventListener('pointerdown', downHandler); | |
return () => document.removeEventListener('pointerdown', downHandler); | |
}, [f, ref]); | |
}; | |
export default useOutsideClick; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
upHandler를 추가하지않으면 버튼을 클릭했을때 모달을 여는 버튼을 클릭시 downHandler에 의해서 모달이 닫힌 후 바로 열림.
모달이 닫힌 후에는 click 이벤트에 의해 바로 열리는 것을 방지하기 위해 upHandler에서 click 이벤트를 캡쳐방식으로 가로채서 이벤트 전파를 정지시킴.