Why does adding a ref in a `react-hook-form` input element prevent the form from rendering?

Viewed 32

I'm new in the React world, and some people recommended that I use react-hook-form for my forms. I don't know if it's relevant to mention, but I use Tailwind CSS. Here, is my problem:

When I'm parsing ref = {register} at the end of an input nothing renders. Without ref = {register} everything works perfectly. If someone can help, I'd be delighted.

Here is my code :

import './App.css';
import React from "react";
import { useForm } from "react-hook-form";

function App() {
  const {register, handleSubmit}  = useForm();
  const onSubmit = data => console.log(data);
  return (
    < form onSubmit={handleSubmit(onSubmit)}>
      <input type='text' placeholder='Email' name='email' ref = {register} />
      <input type='password' placeholder='Password' name='password' ref = {register}/>
      <input type='submit'/>
    </form>
  );
}

export default App;
1 Answers

You don't have to use a ref, and besides register is a function, not a ref. With latest version of React Hook Form (current is 7.34.0) you have to pass register as {...register("name_of_the_field")}.

    function App() {
     const {register, handleSubmit}  = useForm();
     const onSubmit = data => console.log(data);
     return (
     <form onSubmit={handleSubmit(onSubmit)}>
      <input type='text' placeholder='Email' name='email' {...register('password')} />
      <input type='password' placeholder='Password' name='password' {...register('password')}/>
      <input type='submit'/>
     </form>
     );
    }
Related