I’m using Nextjs + Typescript to make a toy project
and I’m having a problem when using createPortal to create a Modal.
I got a problem with render in Browser.
why doesn’t it work?
I have done a lot of trying googling but i couldn’t solve it.
Plz help me.
HOC/Portal.tsx
import { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
interface Props {
children: any;
}
const Portal: React.FC<Props> = ({ children }) => {
const ref = useRef<HTMLDivElement | null>(null);
const [mounted, setMounted] = useState(false);
useEffect(() => {
ref.current = document.querySelector("overlay-root");
setMounted(true);
return () => setMounted(false);
}, []);
return mounted ? createPortal(children, ref.current!) : null;
};
export default Portal;
src/Components/layout/Header.tsx
...
{isLoginModal && (
<Portal>
<Login
onChangeLoginModal={onChangeLoginModal}
onChangeLoginState={onChangeLoginState}
isLoginState={isLoginState}
isLoginModal
/>
</Portal>
)}
...
pages/_documents.tsx
...
render() {
return (
<Html>
<Head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="target-densitydpi=device-dpi, user-scalable=0, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, width=device-width"
></meta>
<link
href="https://fonts.googleapis.com/css2?family=Dongle&family=Noto+Sans+KR:wght@500&family=Roboto:wght@500&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
{/* here */}
<div id="overlay-root"></div>
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;