Capítulo 19 de 29

Chapter 19: Focus Management

Core Idea

The library intentionally has no built-in focus-on-error behavior (it doesn't know your markup), so focusing the first invalid field on a failed submit is a few lines you write yourself in onSubmitInvalid.

Key Concepts

  • onSubmitInvalid fires when handleSubmit() runs but validation fails — the natural hook point for focus management.
  • DOM approach: query [aria-invalid="true"] and call .focus() on the first match — TanStack Form's fields set aria-invalid as part of their accessibility state, so this selector is reliable without extra wiring.
  • React Native has no DOM query: without document.querySelector, track input refs yourself and iterate the form's error map to find and focus the first problematic field's ref.

Code Examples

onSubmitInvalid() {
  const invalidInput = document.querySelector('[aria-invalid="true"]') as HTMLInputElement
  invalidInput?.focus()
}
  • What it demonstrates: the minimal web implementation — find the first ARIA-invalid element, focus it.

Key Takeaways

  1. This is opt-in, not automatic — a form with no onSubmitInvalid focus logic will not move focus anywhere on a failed submit.
  2. Rely on aria-invalid rather than a custom "has error" class — it's already set by the library and doubles as the accessibility signal screen readers use.
  3. On React Native, plan for ref-tracking from the start (there's no DOM to query) — see ch021 for the React Native field pattern this builds on.

Connects To

  • Ch017 Submission Handling: onSubmitInvalid as the counterpart to a successful onSubmit.
  • Ch021 React Native: the ref-tracking difference on non-DOM renderers.