Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Expected server HTML to contain a matching <body> in <div>

I get the above mentioned warning in the console. I don't understand why. I have two matching <body> tags in index.js file. The complete warning is -

Warning: Expected server HTML to contain a matching <body> in <div>.
    in body (at pages/index.js:12)
    in div (at pages/index.js:11)
    in div (at pages/index.js:7)
    in Index (at _app.js:8)
    in MyApp
    in Container (created by AppContainer)
    in AppContainer

Following the index.js file I'm using. I'm using Next.js with tailwindcss.

import Head from "next/head"
import SideNavbar from "../components/SideNavbar"
import MainPage from "../components/MainPage"

const Index = () => {
  return (
    <div className="mx-auto">
      <Head>
        <title>Manchester United</title>
      </Head>
      <body className="min-h-screen">
        <div className="flex flex-row">
          <SideNavbar />
          <MainPage>
            <div className="text-center px-2 py-6 text-5xl font-bold text-gray-200">
              Manchester United
            </div>
          </MainPage>
        </div>
      </body>
    </div>
  )
}

export default Index

The warning goes away if I replace the <body> tag with a <div> tag. The two custom components I use, <SideNavbar /> and <MainPage />, don't use any <body> tags.

like image 684
theairbend3r Avatar asked Sep 12 '25 09:09

theairbend3r


2 Answers

Your HTML isn't correct. You cannot have a body-Tag inside a div-Tag. A basic HTML-Structure looks like this

<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div></div>

</body>
</html>
like image 124
Dimitri Avatar answered Sep 14 '25 23:09

Dimitri


As React works, your React application is "injected" to HTML element which you define at ReactDOM.render:

ReactDOM.render(<App />, document.getElementById('root'));

But, this element is already a child of <body> element.

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

Your error is just a variation of the same thing but as server-side rendering (Next.js) error.


By using Next.js, this HTML is hidden from you (check the HTML in the "vanilla" example in codesandbox attached).

Also, you can inspect the DOM tree at source tab in dev tools, there you will notice that two <body> elements exist.

Here is a small codesandbox code which demonstrates the error:

Edit peaceful-bas-yhbof

like image 36
Dennis Vash Avatar answered Sep 14 '25 22:09

Dennis Vash