参考にしたドキュメント
Next.js公式ドキュメント - Text content does not match server-rendered HTML
(https://nextjs.org/docs/messages/react-hydration-error)
概要
以下のエラーに遭遇したため、その対処法を推測し調べたところ解明した
Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used
結論
今回のケースはHTMLとクライアントサイドでのレンダリング結果が一致していないのが原因。
さらにかみ砕くと、Propsで受け取るchildrenの明記の仕方が良くなかった。
今回発生したコード
import Head from "next/head";
import React from "react";
interface Props {
children?: React.ReactNode;
}
const Hoge = ({ children }: Props) => {
return (
<div>
<Head>
<link rel="icon" href="/favicon.ico" />
</Head>
<header>
<img src="/images/profile.png" />
</header>
<main>{children}</main>
</div>
);
};
export default Hoge;
修正
公式ドキュメントに書いてある通り、HTML タグのネストが正しくない場合に起こることが多いとのこと。
今回の場合、タグがnullなのに存在することで無駄なネストが存在することでエラーが発生したと思われる。
なので、その無駄なタグを処理してあげる。
import Head from "next/head";
import React from "react";
interface Props {
children?: React.ReactNode;
}
const Hoge = ({ children }: Props) => {
return (
<div>
<Head>
<link rel="icon" href="/favicon.ico" />
</Head>
<header>
<img src="/images/profile.png" />
</header>
{children && <main>{children}</main>}
</div>
);
};
export default Hoge;
まとめ
childrenをnull許容するケースはたまに見るが、この記述法が良いのか、もしくは原因の解消法として正しいのかは少し不安が残るが、個人的には問題ないと思っている。
可読性が少し落ちるのかもしれないのかな?とも思うので要検討。
良い案やおすすめがあればぜひコメントください。