Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Next.js throws error "Text content does not match server-rendered HTML"

I created fresh Next.js project and only added really simple component:

const IdPanel = () => {
  const [id] = useState(`${Math.random()}`);

  return (
    <div>
      <h1 id={id} className={id}>
        {id}
      </h1>
    </div>
  );
};

When I run the dev server it throw an error in my browser "Text content does not match server-rendered HTML".

What’s the solution to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Versions:

"next": "13.0.3",
"react": "18.2.0",
"react-dom": "18.2.0"

>Solution :

As the comment suggests, id on the server doesn’t match the id on the client.

EDIT:
Simplest method is to have useState and then set the state in the useEffect

Other methods:

You can use getStaticProps or getServerSideProps to generate the random id, and then send it to the client.

In the first case, the page will be generated only once when the server starts. So when ever you try to access that page you will get the same result, because it has generated static HTML and id wont change.

In the other case the page will be generated on the server for every request to get that page. So you should get the different id each time.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading