How to focus IonInput with setFocus method

I am trying to use the setFocus method but it’s not clear to me how to correctly call it without using useRef. (Tried solution from this post - Set focus to IonInput - #2 by mikrochipkid) The ref seems to be already used by our Yup validation, as it will render it as an error.

Attempt 1:

    useEffect(() => {
        if (show2fa) {
            twoFactorInput?.current?.setFocus();
        }
    }, [setFocus, show2fa]);

Result: Breaks our Yup validation that we use in combination with useForm hook: https://react-hook-form.com/api/useform

Attempt 2:

  const {
       register,
       handleSubmit,
       setFocus,
       resetField,
       formState: { errors },
   } = useForm({
       defaultValues: {} as loginFormType,
       resolver: yupResolver(loginFormSchema),
   });

   useEffect(() => {
       if (show2fa) {
           setFocus('twoFactorToken');
       }
   }, [setFocus, show2fa]);

....

 <IonInput
       {...register('twoFactorToken')}
 />

Result: No errors but the input never focusses.

Is there a maybe a way to call the ionic setFocus on the registered reference? I’m not sure how to find this.

Thanks a lot

I am facing the same problem and have not found a solution yet. Is anyone else experiencing this issue?

same, its been a year, do you have any work around regarding this issues?

Hi, condinoaljoseph. This is my walkaround: I’ve created a custom hook that receives an error object from the react hook form and uses the setFocus method from Ionic.

Custom hook

// Define a custom hook for handling errors and focusing on the first error field
export function useFocusOnFormError(errors: FieldErrors<FieldValues>) {
  const focusFirstError = () => {
    const firstErrorKey = Object.keys(errors)[0];
    const firstError = errors[firstErrorKey];

    if (firstError && firstError.ref && firstError.ref.setFocus) {
      firstError.ref.setFocus();
    }
  };

  return {
    focusFirstError,
  };
}

React component

const {
    handleSubmit,
    register,
    getFieldState,
    setValue,
    formState: { errors, isSubmitting },
  } = useForm<User>({
    mode: 'onBlur',
    reValidateMode: 'onBlur',
  });

  const { focusFirstError } = useFocusOnFormError(errors);

This is going to trigger with errors changes. If you want to revalidate when the user submits the form, you can call the method in the on-click method:

<IonButton
    type="submit"
    color="primary"
    expand="block"
    onClick={focusFirstError}
>     
   'Create account'
</IonButton>

I hope that the information I have provided is useful to you.

Best,

Matias Oliva

1 Like

Thanks for this work around. Its very useful on handling focus management on errors.

But for handling focus management on other fields we need to re assign it to other ref sa @SaroGFX stated.