简体   繁体   中英

Why is using a table in Next.js throwing a hydration error?

In this code, I have a problem on using tag. when I use tr tag the error occurs.It says that Unhandled Runtime Error Error: Hydration failed because the initial UI does not match what was rendered on the server.

import React from 'react'
import {useState} from 'react'


const port = () => {
  return (
    <div className="ml-14">
      <div className="profile">
        <h1 className="mt-5 font-bold">Nasvirat</h1>
        <p className="mt-5">total balance : </p>
      </div>
      <div className="portfolio">
        <h2 className="mt-7">Holding</h2>

        <table>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
        </tr>
        <tr>
          <td>Peter</td>
          <td>Griffin</td>
        </tr>
        <tr>
          <td>Lois</td>
          <td>Griffin</td>
        </tr>
        </table>
      </div>
    </div>
  )
}

export default port

do u have idea why this happen and how to fix it.

This is an open issue in the Next.js repo. The issue is coming from the fact that you do not have <tbody> or <thead> wrapping your rows.

Although they are not specified to mandatory for correctly rendering the table, next.js somehow cannot identify this.

My assumption is there is a difference in the code that is run on the server and on the client because of this.

Try adding this:

        <table>
        <tbody>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
        </tr>
        <tr>
          <td>Peter</td>
          <td>Griffin</td>
        </tr>
        <tr>
          <td>Lois</td>
          <td>Griffin</td>
        </tr>
        </tbody>
        </table>

It is noteworthy, that browsers add a tbody inside the table automatically . So even if you skip it, it will end up in your DOM code. This is for older HTML versions as mentioned in the answer. Here is a demo for that. Check the code and compare it with the actual DOM that is rendered.

I am guessing next.js does not add the tbody by default when generating on server side. This is what causes the mismatch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM