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?

More than 1 year has passed since last update.

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

Posted at

はじめに

  • 初めて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

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?