HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🌟
Programmers 최종 플젝 6조
/
[프론트] TWL
[프론트] TWL
/
Next.js에서 Modal useClickAway 적용하기
Next.js에서 Modal useClickAway 적용하기
Next.js에서 Modal useClickAway 적용하기

Next.js에서 Modal useClickAway 적용하기

생성일
Dec 20, 2021 11:45 AM
태그
Next.js
Issue
작성자
해결 완료
해결 완료

🔥 문제

현재 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;
 

결과

오류 없이 잘 작동한다!
 

👏🏻 참고자료