🔥 문제
현재
NavModal
에서 window
를 피하기 위해 작업하였으나...결과적으로
useClickAway
이래로 onClose
가 동작하지 않았다.아무래도, 첫
setEl
할 때, 값을 null
로 처리를 하게 되고, 그렇기 때문에
handleClose
가 제대로 선언이 되지 않았던 것이 원인인 듯하다.이를 해결할 수 있는 방법이 무엇일까?
⭐ 해결 방법
원인은
useClickAway
였다.ref
의 경우 객체타입이다. 따라서 useRef
가 바뀔 일은 없으므로 한 번만 동작한다.그런데,
ref.current
는 바뀔 수 밖에 없다. 왜냐하면, ref.current
가 곧 해당 엘리먼트에 매칭되기 때문이다. 따라서
useEffect
에서 ref.current
를 감시하도록 한다.import { useEffect, useRef } from 'react'; const events = ['mousedown', 'touchstart']; const useClickAway = (handler: Function) => { const ref = useRef<HTMLDivElement>(null); const savedHandler = useRef<Function>(handler); useEffect(() => { savedHandler.current = handler; // 핸들러 함수가 변하더라도 다시 지우고 이벤트를 추가시키지 않도록 함. }, [handler]); useEffect(() => { if (!ref.current) return; const element = ref.current; const handleEvent = (e: any) => { if (!element.contains(e.target)) { savedHandler.current(e); } }; for (const eventName of events) { document.body.addEventListener(eventName, handleEvent); } return () => { for (const eventName of events) { document.body.addEventListener(eventName, handleEvent); } }; /* eslint-disable react-hooks/exhaustive-deps */ }, [ref.current]); return ref; }; export default useClickAway;
결과
오류 없이 잘 작동한다!