Blog>
Snippets

Using Custom Hooks to Manage Focus in TanStack Form

Code example for creating a custom React hook to manage focus within a form, especially focusing on the first invalid input when submitting a form with errors.
import { useEffect } from 'react';
import { useForm } from '@tanstack/react-form';
Imports the necessary hooks from React and useForm from TanStack Form.
export function useFocusInvalidInput(form) {
  useEffect(() => {
    if (form.formState.isSubmitted && !form.formState.isValid) {
      const firstInvalidName = Object.keys(form.formState.errors)[0];
      const firstInvalidInput = document.querySelector(`[name="${firstInvalidName}"]`);
      if (firstInvalidInput) {
        firstInvalidInput.focus();
      }
    }
  }, [form.formState.isSubmitted, form.formState.isValid, form.formState.errors]);
}
Defines a custom hook that focuses on the first invalid input if the form has been submitted but is invalid. It uses useEffect to observe changes to the form's submission state, validity, and errors.
const form = useForm({
  defaultValues: {
    username: '',
    password: '',
  },
  onSubmit: async (values) => {
    console.log(values);
  },
});
useFocusInvalidInput(form);
Uses the useForm hook from TanStack Form to create a form instance and then applies the custom useFocusInvalidInput hook to the form. This ensures that if the form is submitted with errors, the first invalid input receives focus.