1. 문제
<div id=”modal” />을 layout안에 둬서, 이 태그에 createPortal을 이용하여 포탈을 만들어 모달을 구현하고자한다. 그런데, 사진과 같은 에러가 자꾸 발생했다.
기존에 modal 태그를 layout에 넣었을 때 코드이다.
// src/app/layout.tsx
export default function RootLayout({ children }: PropsWithChildren) {
return (
<html lang="ko" className={roboto.className}>
<div id="modal" />
<body className="bg-white text-body text-black">{children}</body>
</html>
);
}
// src/components/ModalPortal.tsx
export default function ModalPortal({ chxildren }: PropsWithChildren) {
const [modalRoot, setModalRoot] = React.useState<HTMLElement>(null);
useEffect(() => {
setModalRoot(document.getElementById('modal'));
}, []);
if (!modalRoot) return null;
return createPortal(children, modalRoot);
}
2. 해결 방법
modal 태그를 body태그 안으로 옮기니 해결되었다.
export default function RootLayout({ children }: PropsWithChildren) {
return (
<html lang="ko" className={roboto.className}>
<body className="bg-white text-body text-black">
<div id="modal" />
{children}
</body>
</html>
);
}
원인
기본적인 HTML문서 구조는 다음과 같다.
<!DOCTYPE html>
<html>
<head>
<title>Document Title</title>
</head>
<body>
<!-- 여기에 div 태그를 포함한 모든 컨텐츠를 넣을 수 있습니다 -->
<div>
여기에 내용이 들어갑니다.
</div>
</body>
</html>
위와 같이, html태그 안에는 head와 body 두 개의 태그만이 존재해야 한다.