記事一覧に戻る

Next13のチュートリアルをしてたら「If you need interactivity, consider converting part of this to a Client Component.」というエラーにぶつかった話

2023-09-141 min read技術記事
#error#初心者#備忘録#Next.js

はじめに

  • 初めてNext.jsの13のチュートリアルをしており、いい感じに実装してたのにボタンにonClickを実装しようとしたら、

スクリーンショット 2023-09-14 4.08.49.png

Event handlers cannot be passed to Client Component props.
  <button style={{...}} onClick={function} children=...>
                                ^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.

とかいうエラーが出た。

解決方法

これより、「Next.js 13ではデフォルトで全ての関数がサーバーコンポーネントとなるためクライアントサイドのアクティビティを有効にするには、’use client’;をつけるだけでいいらしい。

例:

まじでコードの冒頭に入れるだけ。

注:Next 13以外で実行するとエラーが発生する可能性がある。

'use client';

export default function Home() {

    const fetchCatImage = async () => {
      const res = await fetch('https://api.thecatapi.com/v1/images/search');
      const data = await res.json();
      console.log(data);
    };

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        fontFamily: 'sans-serif',
        justifyContent: 'center',
        height: '100vh',
      }}>
        <h1>猫画像を取得</h1>
        <p>
          <img
            src="https://cdn2.thecatapi.com/images/4kc.gif"
            width={500}
            height="auto"
          />
        </p>
        <button style={{ marginTop:"18"}} onClick={fetchCatImage}>
          次の猫画像
        </button>
    </div>
  )
}

うん!いい感じ。 スクリーンショット 2023-09-14 4.15.26.png