0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】Hydration failed? DOMを正しく処理しよう【TypeScript】【エラー対処】

Last updated at Posted at 2024-12-27

参考にしたドキュメント

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;

{error0}.png

修正

公式ドキュメントに書いてある通り、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;

{error1}.png

まとめ

childrenをnull許容するケースはたまに見るが、この記述法が良いのか、もしくは原因の解消法として正しいのかは少し不安が残るが、個人的には問題ないと思っている。
可読性が少し落ちるのかもしれないのかな?とも思うので要検討。
良い案やおすすめがあればぜひコメントください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?