Ivomasterche
Ivomasterche

Reputation: 107

NextJS 13 Hydration failed error, when using Modal Component

Hello I am using the SRC folder with APP router nextjs 13 and trying to set up simple Modal message, which is visualized correctly, but throws the following Error in the Console:

Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching in .

I've tried to put the modal in different places, in the layout.tsx, in provider, in page, as a component, or directly in the page, with wrapping div and <></> but with no luck. I guess this has something to do with the fact that when I inspect the code, the code of the modal is always just after the body tag, and not where the component code is positioned.

layout.tsx


...

return (
    <html lang="en">
      <body className="min-h-screen">
        <Providers>{children}</Providers>
        {/* Allow more height for mobile menu on mobile */}
        <div className="h-40 md:hidden" />
      </body>
    </html>
  );

page.jsx

import Modal from "react-bootstrap/Modal";
export default function Home() {
 return (
    <>
      <SomeComponents/>
<Modal show={true}>Text</Modal>
    </>
  );
}

I have tried with clean skeleton nextjs13 with the same result.

Upvotes: 1

Views: 1952

Answers (2)

Tabish Zaman
Tabish Zaman

Reputation: 292

Use useEffect for setting state true, dont set true directly. here is a sample code.

import { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';

interface PopupProps {
    item: any
}
function Popup({ item }: PopupProps) {

    const [show, setShow] = useState(false);

    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    useEffect(() => {
        setShow(true);  // <---- 
      }, []);

    return (
        <div>
            <Modal show={show} onHide={handleClose}
                size='lg'
                centered
                className={`old-modal`}
                keyboard={true}>
                <Modal.Header closeButton>
                    <Modal.Title>Modal heading</Modal.Title>
                </Modal.Header>
                <Modal.Body>Woohoo, you are reading this text in a modal! 
                </Modal.Body>
            
            </Modal>
        </div>
    );
}

export default Popup;

Upvotes: 3

Shodipo Ayomide
Shodipo Ayomide

Reputation: 1450

Had this problem once before, the error you're seeing typically happens when the markup that the client tries to render during hydration differs from what the server renders.

You can use dynamic imports with the ssr: false option to fix this,

You can read more about Dynamic imports and code splitting with Next.js here

Upvotes: 1

Related Questions