👏

【Next13】Error: Event handlers cannot be passed to Client Component pro

2023/05/04に公開

はじめに

チェスアプリを作っており、写真の駒が掴まれた時の挙動を実装するためにonMouseDownをコマを囲っている<div>に使ったところ、以下のようなエラーが出た。

Error: Event handlers cannot be passed to Client Component props.
  <div onMouseDown={function} className=... children=...>
                   ^^^^^^^^^^
If you need interactivity, consider converting part of this to a Client Component.
    at stringify (<anonymous>)

解決

Next.js 13から、デフォルトのコンポーネントはすべてServer Componentになったので、クライアントサイドのインタラクティビティを実現するにはuse clientを使用する必要があります。

そのため、onMouseDownを使用しているファイルの先頭にuse clientを追加すると解決しました。

参考資料

NextJS 13 <button onClick={}> Event handlers cannot be passed to Client Component props

Discussion