Capítulo 6 de 29

Chapter 6: React Quick Start

Core Idea

The minimal React form is two pieces: useForm({ defaultValues, onSubmit }) creates the form instance, and form.Field (a render-prop component) wires an individual input to that instance's state.

Key Concepts

  • useForm needs at least defaultValues (used both to seed state and to infer every field's type) and typically onSubmit.
  • form.Field takes a name (type-checked against defaultValues's keys) and a children render function receiving the field API — field.state.value, field.handleChange, field.handleBlur.
  • Field names are validated at compile time against the shape of defaultValues — a typo in name is a type error, not a silent runtime miss.

Code Examples

const form = useForm({
  defaultValues: { age: 0 },
  onSubmit: ({ value }) => console.log(value),
})

return (
  <form.Field
    name="age"
    children={(field) => (
      <input
        value={field.state.value}
        onChange={(e) => field.handleChange(e.target.valueAsNumber)}
      />
    )}
  />
)
  • What it demonstrates: the two-piece minimal shape — form instance + one controlled field — with no validation attached yet.

Worked Example

Starting from nothing: call useForm with a defaultValues object shaped like your eventual form data (here, { age: 0 }). Render one form.Field per input, matching name to a key in defaultValues. Inside the render function, read field.state.value for the current value and call field.handleChange on every change event — note the explicit e.target.valueAsNumber (not .value) because the field is typed as a number, another instance of the library's "types come from your data" philosophy (ch003). No <form onSubmit> handler or button is required yet at this stage; submission wiring is ch017's concern.

Key Takeaways

  1. defaultValues is not just an initial-value convenience — it is the single source of truth TypeScript uses to type every field name and value in the form.
  2. form.Field's children render-prop is the seam every UI-library integration (ch018) and every framework adapter (ch029) hangs off of.
  3. This minimal shape has no validation, submission button, or error display — those are each their own guide (ch008, ch017).

Connects To

  • Ch007 Basic Concepts: the fuller mental model (form instance / field instance / field state / subscriptions) behind this example.
  • Ch008 Form Validation: adding validators to this same form.Field.
  • Ch017 Submission Handling: wiring an actual submit button/handler.