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?

【更新予定】react-hook-formの使い方 備忘録

Posted at

registerとController

register

HTMLタグの<input/><select/>に対してのみ使用する。
昨今のUIライブラリを利用する流れだと、あまりこちらは使わない(気がする)。

使用例
import { useForm } from "react-hook-form"

export default function App() {
  const { register, handleSubmit } = useForm({
    defaultValues: {
      firstName: "",
      category: "",
    },
  })

  return (
    <form onSubmit={handleSubmit(console.log)}>
      <input
        {...register("firstName", { required: true })}
        placeholder="First name"
      />
      
      <select {...register("category")}>
        <option value="A">Category A</option>
        <option value="B">Category B</option>
      </select>

      <input type="submit" />
    </form>
  )
}

Controller

Ant DesignMUIなどの外部UIライブラリに対して、使用する場合に使う。
UIライブラリの利用が流行っているので、基本的にはこちらを使う。

使用例
import ReactDatePicker from "react-datepicker"
import { useForm, Controller } from "react-hook-form"

type FormValues = {
  ReactDatepicker: string
}

function App() {
  const { handleSubmit, control } = useForm<FormValues>()

  return (
    <form onSubmit={handleSubmit((data) => console.log(data))}>
    
      <Controller
        control={control}
        name="ReactDatepicker"
        render={({ field: { onChange, onBlur, value, ref } }) => (
          <ReactDatePicker
            onChange={onChange} // send value to hook form
            onBlur={onBlur} // notify when input is touched/blur
            selected={value}
          />
        )}
      />

      <input type="submit" />
    </form>
  )
}

【外伝】 shadcn/ui を使う場合

shadcn/uireact-hook-formを扱う場合、
react-hook-formライブラリのラッパーコンポーネント<Form>が提供されています。

使用例
const form = useForm()

<FormField
  control={form.control}
  name="username"
  render={({ field }) => (
    <FormItem>
      <FormLabel>ユーザーネーム</FormLabel>
      <FormControl>
        <Input placeholder="shadcn" {...field} />
      </FormControl>
      <FormDescription>これはあなたの公開表示名です</FormDescription>
      <FormMessage />
    </FormItem>
  )}
/>

また、上記を使ってコンポーネント化した例もあるので、併せて確認したい。

参考

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?