Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus a ref using React-Hook-Form

How do you implement set focus in an input using React-Hook-Form, this is what their FAQ's "How to share ref usage" code here https://www.react-hook-form.com/faqs/#Howtosharerefusage

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

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={(e) => {
        register(e)
        firstNameRef.current = e // you can still assign to ref
      }} />
      <input name="lastName" ref={(e) => {
        // register's first argument is ref, and second is validation rules
        register(e, { required: true })
      }} />

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

I tried set focusing the ref inside useEffect but it doesn't work:

useEffect(()=>{
   firstNameRef.current.focus();
},[])

Neither does inside the input:

<input name="firstName" ref={(e) => {
    register(e)
    firstNameRef.current = e;
    e.focus();
}} />
like image 466
Twirlman Avatar asked Sep 08 '20 15:09

Twirlman


People also ask

How do you focus something on next render With React hooks?

Focus Something on Next Render with React Hooks It's set to false initially. Next, we add the toggleEditing function to call setEditing function to the negated value of the isEditing state. Then we create the inputRef ref that lets us assign to the input element below.

How do you use onChange in React hook form?

React Hook Form is focusing on uncontrolled inputs, which means you don't need to change the input value via state via onChange . This means you don't need value at all, and in fact, you only need to set defaultValue for the initial input value. import { useForm } from 'react-hook-form/dist/index.

How do you use setFocus in React hook form?

setFocus:(name: string, options: SetFocusOptions) => void This method will allow users to programmatically focus on input. Make sure input's ref is registered into the hook form.


1 Answers

You can set the focus using the setFocus helper returned by the useForm hook (no need to use a custom ref):

 const allMethods = useForm();
 const { setFocus } = allMethods;

 ...

 setFocus('inputName');

https://react-hook-form.com/api/useform/setFocus

like image 155
Bryce Avatar answered Sep 19 '22 20:09

Bryce