Capítulo 12 de 29

Chapter 12: Form Groups

Core Idea

<form.FormGroup> scopes a subset of a form's fields into an independently-validated, independently-submittable sub-form — the building block for multi-step wizards where each step has its own validation gate.

Key Concepts

  • A form group wraps a name that must match a top-level key in defaultValues holding an object (e.g. step1: { name: "" }).
  • Independent validation: validators on the group only checks that group's slice of state, not the whole form.
  • onGroupSubmit: fires when that group's own submit/advance action succeeds — commonly used to advance a wizard's step state, distinct from the parent form's onSubmit.
  • The parent form's own handleSubmit remains the final, whole-form submission — a form group is a checkpoint along the way, not a replacement for it.

Code Examples

const [step, setStep] = useState(0)
const form = useForm({ defaultValues: { step1: { name: '' }, step2: { age: 0 } } })

{step === 0 && (
  <form.FormGroup
    name="step1"
    validators={{ onChange: z.object({ name: z.string().min(2) }) }}
    onGroupSubmit={() => setStep(1)}
    children={(group) => <button onClick={() => group.handleSubmit()}>Next Step</button>}
  />
)}
{step === 1 && (
  <form.FormGroup
    name="step2"
    children={(group) => <button onClick={() => form.handleSubmit()}>Submit Form</button>}
  />
)}
  • What it demonstrates: step 1 validates and advances via its own group; step 2's button calls the parent form's handleSubmit directly to finish the whole flow.

Key Takeaways

  1. Reach for FormGroup specifically for multi-step/wizard UX where each step needs its own pass/fail gate — for a single flat form, plain field-level validators (ch008) are simpler.
  2. A group's onGroupSubmit and the parent form's onSubmit are two separate callbacks — the last step in a wizard typically calls form.handleSubmit() directly (as shown), not the group's.
  3. Groups nest under a defaultValues key that must already be an object — restructure defaultValues around your steps before reaching for FormGroup.

Connects To

  • Ch008 Form Validation: the same validator timing/scoping model, applied at group scope here.
  • Ch017 Submission Handling: how the final group's submit reaches the parent form's onSubmit.