9
8

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 3 years have passed since last update.

【React Hook Form】Controllerの中でonChangeを使う方法

Posted at

React Hook Form の <Controller> を使っている時、renderの中でonChangeを定義しても上手く動かない。

// これは動かない
<Controller
  control={control}
  name="email"
  render={({field}) => (
    <TextField
      {...field}
      onChange={customOnChange}
    />
  )}
/>

なぜ動かないかというと、fieldに含まれるonChangeを呼び出していないからだ。

なので、自作のonChangeとfield.onChangeの両方を呼び出してやる必要がある。

// これで動く
<Controller
  control={control}
  name="email"
  render={({field}) => (
    <TextField
      {...field}
      onChange={(e) => {
        field.onChange(e)
        handleOnChange(e)
      }}
    />
  )}
/>

この理屈でいくと、register の時も同じなのかなと思ったが、registerの方はこんなことしなくても正常に動作していた。

[参考]
https://stackoverflow.com/questions/66936135/react-hook-form-how-to-can-i-use-onchange-on-react-hook-form-version-7-0

9
8
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
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?