Next.js의 Document is not Defined 오류 해결법 - MNC-TEAM/gugumo_frontend GitHub Wiki

Document is not Defined 오류

 ⨯ src\components\modal\custom-modal.tsx (23:7) @ document
 ⨯ ReferenceError: document is not defined
    at CustomModal (./src/components/modal/custom-modal.tsx:33:24)
digest: "1378868926"
  21 |         }
  22 |       </>,
> 23 |       document.body
     |       ^
  24 |     )
  25 | }

커스텀 모달을 작성중에 React Portal을 사용할경우 Next.js에서 해당 오류가 발생하는 문제가 생김

해결방안

Next.js의 App router는 SSR 기반으로 작성을 하기 때문에

서버 사이드에서는 실행되지 않고 클라이언트에서만 발생하게 하면 되는 문제 라는것을 깨달았습니다.

const modals = useAppSelector(state=>state.modal);
  const dispatch = useAppDispatch();
  const [mounted, setMounted] = useState(false);

  useEffect(()=>{
    setMounted(true);
  },[]);

  if(!mounted){
    return null;
  }

  return createPortal(
      <>
        {
          modals.map((info,index)=>{
            const {Component,isOpen} = info;
            const onClose = ()=>{
              const html = document.querySelector('html');
              if(!html) return;
              html.style.overflowY = "auto";
              dispatch(close(Component));
            }
            return <Component key={index} isOpen={isOpen} onClose={onClose}/>
          })
        }
      </>,
      document.body
    )

제가 해결한 방법은 useEffect을 이용해서 컴포넌트가 불러와지면 createPortal을 실행하게 해줬습니다.