How to use React Hook Form with Typescript (Input Component)

Viewed 15031
2 Answers

OK here the problems:

  1. you need to add register to props in the Input component props declaration
  2. you must use the register passed as prop, not a new one created with useForm in Input component
  3. the input element is missing the name attribute

here the working <Input> component with comments:

import React, { InputHTMLAttributes } from "react";
import {
  FieldValues,
  UseFormRegister,
  // useForm, // don't need this import
} from "react-hook-form";

interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
  id: string;
  label: string;
  register: UseFormRegister<FieldValues>; // declare register props
}

const Input: React.FC<InputProps> = ({ id, label, register, ...rest }) => {
  //const { register } = useForm(); // don't use a new `register`, use the one from props

  return (
    <div className="input-block">
      <label htmlFor={id}>{label}</label>
      <br />
      <br />
      
      {/* react-hook-form v6 */}
      {/* you must declare the `name` attribute on the input element */}
      <input name={id} type="text" id={id} ref={register} {...rest} />

      {/* react-hook-form v7 */}
      {/* In v7 the register() function returns all the needed properties */}
      {/* see: https://dev.to/bluebill1049/what-s-coming-in-react-hook-form-version-7-4bfa */}
      {/* <input type="text" id={id} {...register(id)} {...rest} /> */}
    </div>
  );
};

export default Input;
Related