【React】React Hook Formのregisterをコンポーネントのpropsに渡す

Controllerを使用せずにコンポーネントに対してReact Hook Formのregisterを渡したいことがあったのでメモ。

"use client";
import Text from "@/components/Text";
import { useForm } from "react-hook-form";

type SampleForm = {
  sampleText: string;
};

export default function Home() {
  const { register, handleSubmit, watch } = useForm<SampleForm>();

  const sampleText = watch("sampleText");
  console.log(sampleText);

  const onSubmit = (data: SampleForm) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Text label="サンプルインプット" register={register("sampleText")} />
      <button type="submit">Submit</button>
    </form>
  );
}
import { InputHTMLAttributes } from "react";
import { UseFormRegisterReturn } from "react-hook-form";

type InputProps = InputHTMLAttributes<HTMLInputElement> & {
  label: string;
  register: UseFormRegisterReturn;
};

const Text = ({ label, register, ...otherProps }: InputProps) => {
  return (
    <div>
      <label>{label}</label>
      <input {...register} {...otherProps} />
    </div>
  );
};

export default Text;

IT技術ブログ
↓↓「にほんブログ村」のランキングに参加しています。少しでも面白い、参考になったとか思われたらポチッとしていただけると嬉しいです!

にほんブログ村 IT技術ブログへ

にほんブログ村