react hook form setfocus

To set focus on a specific field in React Hook Form, you can use the ref attribute along with the useEffect hook. Here’s an example of how you can achieve this:

import { useForm } from 'react-hook-form';
import { useEffect, useRef } from 'react';

function MyForm() {
  const { register, handleSubmit } = useForm();
  const fieldRef = useRef(null); // Create a ref for the field you want to focus on

  useEffect(() => {
    // Set focus on the field when the component mounts
    fieldRef.current.focus();
  }, []);

  const onSubmit = (data) => {
    // Handle form submission
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input ref={fieldRef} {...register('fieldName')} />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, the fieldRef is created using the useRef hook. We then assign the ref to the input element using the ref attribute. Finally, inside the useEffect hook, we use fieldRef.current.focus() to set the focus on the field when the component mounts.

Make sure to replace 'fieldName' with the actual name of the field you want to focus on.

Leave a Reply