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のregisterをコンポーネントのpropsに渡す方法

Posted at

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;

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?