DEV Community

Cover image for Next/SSR "document is not defined" error in console FIX
Keep Coding
Keep Coding

Posted on

Next/SSR "document is not defined" error in console FIX

Problem
It's a popular problem when working with Next; Let's use the following example: We are trying to create a modal component, but we get stuck on "document is not defined" error in console :(

"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} />;
}
Enter fullscreen mode Exit fullscreen mode

Fix #1
Should work in any component, both user made, and from any library/UI Kit

const ClientOnlyWrapper = ({ children }) => {
  const [isClient, setIsClient] = useState(false);

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

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

const WrappedModal = () => {
  return(
    <ClientOnlyWrapper>
       <Modal />
    <ClientOnlyWrapper/>
  )
}
Enter fullscreen mode Exit fullscreen mode

Fix #2
Which is included in latest releases of MDB UI Kits, which you can check out here. You don't need to do anything apart from importing it from MDB package:

return (
 { 
   <MDBClientOnly>
     <MDBModal />
   </MDBClientOnly>
 }
)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)