Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 215
Daar44 Avatar asked Dec 06 '25 17:12

Daar44


1 Answers

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>
  );
}
like image 109
Jap Mul Avatar answered Dec 08 '25 07:12

Jap Mul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!