Daar44
Daar44

Reputation: 449

How to use the ref with the react-hook-form react library?

I'm trying to use the react ref with a simple form input defined with react-hook-form library like below (based on the official docs).

Here is the code excerpt I'm dealing with:

<input id="lastName" 
{ ...myRegister('lastName', { 
  required: true,
  onChange: (e) => {
    console.log(e.target.value);
  },
  ref: (input) => { 
    console.log("lastName ref...")
    textInput2 = input
  }
  })
} />

The onChange handler function is working as expected (printing the input current value ) BUT the ref doesn't! - the string lastName ref... isn't printed nor textInput2 initialized with the input variable!

What I'm doing wrong above!?

Can someone please give me an working example of the ref attribute defined with the react-hook-form library?

Upvotes: 16

Views: 30525

Answers (1)

Jap Mul
Jap Mul

Reputation: 18739

The library uses a ref internally to keep track of the value. To add your own ref please check: https://www.react-hook-form.com/faqs/#Howtosharerefusage

import { useRef } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit } = useForm();
  const firstNameRef = useRef(null);
  const onSubmit = data => console.log(data);
  const { ref, ...rest } = register('firstName');

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...rest} name="firstName" ref={(e) => {
        ref(e)
        firstNameRef.current = e // you can still assign to ref
      }} />

      <button>Submit</button>
    </form>
  );
}

Upvotes: 34

Related Questions