Search code examples
reactjsformsreact-hook-formzod

React Hook Form's register function does not work when using custom components


I'm refactoring some code in my app and I noticed that when I moved my input element to be its own reusable component, hook-form's register function stopped working. This can be fixed if you use the plain input element, but I would like to use my own component. Here's a stack blitz with a reproducible example: https://stackblitz.com/edit/react-ts-9bafks?file=App.tsx


Solution

  • If you check what register('text') actually gives you console.log(register("text")) you will see that there is a ref. You have to make your custom inputs to forward that ref.

    const TextInput: FC<Props> = React.forwardRef(({ error, ...props }, ref) => {
      return (
        <div>
          <p> {error} </p>
          <input {...props} ref={ref}/>
        </div>
      );
    });