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 DesignやMUIなどの外部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/ui
でreact-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>
)}
/>
また、上記を使ってコンポーネント化した例もあるので、併せて確認したい。
参考