📝
Next.jsで「Error: Hydration failed」が発生
NExt.jsで「Error: Hydration failed because the initial UI does not match what was rendered on the server.」が発生したので解決する。
Text content does not match server-rendered HTML
解決方法
htmlの構造を見直してください。
私の場合は、react/link(Link) を入れ子にしたことで発生しました。
<Link href="/" className="col mb-5 link" key={post.id}>
<div className="card h-100">
<img className="card-img-top" src="https://dummyimage.com/450x300/dee2e6/6c757d.jpg" alt="..." />
<div className="card-body p-4">
<div className="text-center">
<h5 className="fw-bolder"><Text text={post.properties.Name.title} /></h5>
<div className="d-flex justify-content-center small text-warning mb-2">
<div className="bi-star-fill"></div>
<div className="bi-star-fill"></div>
<div className="bi-star-fill"></div>
<div className="bi-star-fill"></div>
<div className="bi-star-fill"></div>
</div>
{date}
</div>
</div>
<div className="card-footer p-4 pt-0 border-top-0 bg-transparent">
<div className="text-center">
<Link className="btn btn-outline-dark mt-auto link" href={`/blog/detail/${post.id}/`}>記事を読む</Link>
</div>
</div>
</div>
</Link>
Linkコンポーネントは実際のdomを見るとaタグ
になっているので、aタグ
配下にaタグ
が配置されてことになります。
htmlのコンテンツモデルとして、それは許されていません。
参考記事
他にpタグ
の中にdivタグ
を入れたりしても発生します。
htmlのコンテンツモデルを守ってね!ということ。
原因
reactではvalidateDOMNestingという警告が出るみたいですが、Nextが「サーバーが返すHTMLとClientが作成するHTMLが一致しない」と判断し、hydrationに失敗していることがエラーの理由です。
Discussion