LoginSignup
3
2

More than 1 year has passed since last update.

自作(制御)コンポーネントにReact Hook Formでバリデーションをかける

Last updated at Posted at 2021-06-29

やりたい事

React Hook Form を使って自作(制御)コンポーネントにバリデーションをかける。

やり方

テキストを入力する以下のようなコンポーネントを作成する。

import React from 'react';

type Props = {
  onChange: (value:string) => void
  value: string
}

const TextInput:React.VFC<Props> = ({onChange, value}) => {
  return (
    <div>
      <input type="text" onChange={(event)=> onChange(event.target.value)} value={value}/>
    </div>
  );
};

export default TextInput;

以下のようにReact Hook Form が用意してくれている Controller というラッパーコンポーネントを利用する。テキストを入力しない状態で送信ボタンをクリックすると入力必須というエラーメッセージが表示されるのが確認できると思います。

import React from 'react';
import TextInput from "~/components/TextInput"
import { useForm, Controller } from "react-hook-form"

const input = () => {
  const { handleSubmit, control, formState: {errors} } = useForm({
    mode: 'onChange',
    defaultValues: { name: ''}
  })

  return (
    <div>
      <h2>フォーム</h2>
      <form onSubmit={handleSubmit(data => console.log(data))}>
        <Controller
          control={control}
          name='name'
          render={({ field: { onChange, value } }) => (
            <TextInput value={value} onChange={onChange} />
          )}
          rules={{ required: '入力必須です!!' }}
          defaultValue=''
        />
        <p>{errors.name?.message}</p>
        <input type="submit" />
      </form>
    </div>
  );
};

export default input;

参考にした記事

バリデーションにreact-hook-formが便利だった
https://qiita.com/282Haniwa/items/20ecd8addd1517cd622e

React Hook Form Controller
https://react-hook-form.com/api/usecontroller/controller

3
2
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
3
2