0
1

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】React Hook Formのcontrolを引数で設定するための型設定

0
Posted at

概要

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>
      )}
    />
  );
};
0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?