概要
React Hook FormではこちらのReact Hook Form勉強会の内容の記事で紹介されている通り、実装としてはregisterとcontrollerの2つのパターンが用意されています。controllerではUIライブラリのコンポーネントを活用する時等に使用することが多いのですが、その時に必要になるのが「control」オブジェクトです。
今回はcontrolオブジェクトを、引数で引き回す時にどう型設定するかのメモ書きです。
前提
- 使用したreact-hook-formは
7.71.0です。
実装サンプル
React Hook FormではControlというtypeが用意されているので、これを使います。Control型に実際に使用するformの型を設定する形になります。Shadcn UIと組み合わせた実装サンプルは以下になります。
import { FC } from "react";
import { Control } from "react-hook-form";
import {
FormControl,
FormField,
FormItem,
FormLabel,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
type Props = {
control: Control<SampleInputFormType>;
};
export const SampleComponent: FC<Props> = ({ control }) => {
return (
<FormField
control={control}
name={`sampleName`}
render={({ field }) => (
<FormItem>
<FormLabel >
名前
</FormLabel>
<FormControl>
<Input {...field} />
</FormControl>
</FormItem>
)}
/>
);
};