#Modal - document is not defined error in Console

5 messages · Page 1 of 1 (latest)

weary zephyr
#

I'm trying to create a modal component but I'm stuck on "document is not defined" error in console. Any ideas?

''use client";
import { createPortal } from "react-dom";

interface ModalProps {
open: boolean;
}

const Modal = ({ open }: ModalProps) => {
return (
open &&
createPortal(
<>
<div className="modal-dialog">
<h1>Modal</h1>
</div>
<div className="modal-backdrop"></div>
</>,
document.body
)
);
};

export default function Home() {
return <Modal open={true} />;
}

icy rapidsBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

zinc quiver
slow fossil
#

We were facing this issue in the project I'm working on (MDB React Ui Kit). The error appears, because browser-specific objects are not defined on the server. We've created a wrapper-component which solves this issue, and we're going to add it in next release.

Use this workaround to solve this kind of errors for any component or library:

  const [isClient, setIsClient] = useState(false);

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

  return <>{isClient ? children : null}</>;
};

const WrappedModal = () => {
  return(
    <ClientOnlyWrapper>
       <Modal />
    <ClientOnlyWrapper/>
  )
}```
icy rapidsBOT
#
✅ Success!

This question has been marked as answered! If you have any other questions, feel free to create another post

Jump to answer

[Click here](#1192797672717951048 message)