Search code examples
reactjsnext.jsnext.js13

Warning: You are mounting a new body component when a previous one has not first unmounted


I am trying to create a page with dashboard layout and a page with default Next.js 13 layout.

I have a problem on the dashboard page.

When I go to the addresses in the dashboard, the display of menus, items, etc. is correct, and to check the error, I deleted the components and I have only two pages with one link.

But it still gives errors in the browser console:

Warning: You are mounting a new body component when a previous one has not first unmounted. It is an error to render more than one body component at a time and attributes and children of these components will likely fail in unpredictable ways.

Please only render a single instance of and if you need to mount a new one, ensure any previous ones have unmounted first.

and:

Warning: validateDOMNesting(...): cannot appear as a child of <main>.


Solution

  • I have the same error, It seems like you can have HTML and body only in your root layout. Although the doc isn't clear on this, some references can be found here https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts and here https://nextjs.org/docs/app/building-your-application/routing/route-groups#opting-specific-segments-into-a-layout

    So if your root layout looks like this

    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html lang="en">
          <body>{children}</body>
        </html>
      );
    }
    

    Any other layout should not have HTML and body.

    Code for layout in the group will be like this-

    export default function DashboardLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return <section>{children}</section>;
    }
    

    Also, You need to keep below in mind if you have more than 1 group-

    If you create a root layout and then create a layout in one of the groups, it's necessary to have an individual layout in all the groups.