Capítulo 11 de 29

Chapter 11: Arrays

Core Idea

Array fields use mode="array" on a form.Field, addressing individual elements by bracket-index name (`people[${i}].name`), and are mutated through dedicated methods (pushValue, removeValue, insertValue, replaceValue, swapValues, moveValue, clearValues) rather than by reassigning the array yourself.

Key Concepts

  • mode="array" on the parent field turns field.state.value into an array you map over to render one nested form.Field per element.
  • Index-based naming: nested fields are addressed as `arrayName[${index}].subKey` — this is what keeps each array item's sub-fields independently type-checked and independently validated.
  • Mutation methods live on the field API (pushValue, removeValue(index), insertValue(index, value), replaceValue(index, value), swapValues(a, b), moveValue(a, b), clearValues()) — see ch026 for the full FieldApi reference.

Code Examples

<form.Field name="people" mode="array">
  {(field) => (
    <div>
      {field.state.value.map((_, i) => (
        <form.Field key={i} name={`people[${i}].name`}>
          {(subField) => (
            <input value={subField.state.value} onChange={(e) => subField.handleChange(e.target.value)} />
          )}
        </form.Field>
      ))}
      <button onClick={() => field.pushValue({ name: '', age: 0 })}>Add person</button>
    </div>
  )}
</form.Field>
  • What it demonstrates: mapping array elements to nested fields, and appending a new element with pushValue — the same key-by-index pattern extends to removeValue/insertValue/etc.

Key Takeaways

  1. Always use the array mutation methods (pushValue/removeValue/…) instead of mutating field.state.value directly — the direct approach breaks the store's change detection.
  2. Nested array-item fields are addressed by index in the name string, not by a stable ID — if you need stable identity across reorders (drag-and-drop), track a separate key array for React's key prop as shown (key={i} here is illustrative, not necessarily stable across moveValue).
  3. swapValues/moveValue are the two reordering primitives — reach for moveValue for drag-and-drop-style single-item repositioning, swapValues for a straight two-item swap.

Connects To

  • Ch026 Field & Form API Classes: the full method list these mutations belong to.
  • Ch020 Form Composition: reusing an array-field pattern as a composable sub-component.