Next.js Discord

Discord Forum

Modal WITHOUT intercepting route – works but throws Reference Error – helppp

Answered
Nebelung posted this in #help-forum
Open in Discord
NebelungOP
Hey there,
I'm trying to have a simple setup. in browse page i want to have elements with links, i click on them->modal opens. this is working! when i refresh i want to remain on the same page with the modal open.

It's working but after refreshing i'm getting error both in dev and in production:
ReferenceError: document is not defined at Modal

It could be related to <div id="modal-root" /> at browse/layout.tsx .

Repo link: https://github.com/szymonhernik/test-src
I made a simple repo on the nextjs starter. Should maybe the root modal should be somewhere else? I have no clue.

Thank you!!
Answered by joulev
yes it's because you used document.getElementById.

make a isMounted state initialised to false. change it to true in a useEffect.

and only render the modal (and call the document.getElementById) when isMounted is truthy. refer to an example here: https://github.com/vercel/next.js/blob/canary/examples/with-portals/components/ClientOnlyPortal.js
View full answer

7 Replies

Answer
i think it's working now, can you just have a quick look at my code?
const dialogRef = useRef<ElementRef<"dialog">>(null);
  const [mounted, setMounted] = useState(false);

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

  useEffect(() => {
    if (!dialogRef.current?.open) {
      dialogRef.current?.showModal();
    }
  }, [mounted]);

  function onDismiss() {
    router.back();
  }

  return mounted
    ? createPortal(
        <div className="modal-backdrop">
          <dialog ref={dialogRef} className="modal" onClose={onDismiss}>
            {children}
            <button onClick={onDismiss} className="close-button" />
          </dialog>
        </div>,
        document.getElementById("modal-root")!
      )
    : null;
NebelungOP
thank you
you're welcome