Field Arrays

A field array is a repeating group: a list of friends, line items on an invoice, phone numbers. The awkward part is not rendering it but keeping field names, validation errors and touched flags aligned as rows are added and removed. Formik 34,320 's <FieldArray> takes the name of an array inside values and hands you helpers — push, remove, insert, swap, move — that update the array and fix up errors and touched with it.

Adding and removing rows with FieldArrayXML
<Formik initialValues={{ friends: ['jared', 'ian'] }} onSubmit={save}>
  {({ values }) => (
    <Form>
      <FieldArray name="friends">
        {(helpers) => values.friends.map((friend, i) => (
          <div key={i}>
            <Field name={`friends.${i}`} />
            <button type="button" onClick={() => helpers.remove(i)}>-</button>
            <button type="button" onClick={() => helpers.insert(i, '')}>+</button>
          </div>))}
      </FieldArray>
      <button type="submit">Save</button>
    </Form>)}
</Formik>

Two details decide whether this works. Field names are dotted paths — friends.0, or contacts.2.phone for an array of objects — and type="button" on the add and remove buttons is mandatory, since a bare <button> inside a form submits it. The array index is a safe key only while rows are edited in place; once they can be reordered, store a generated id per row. React Hook Form 351,018 's useFieldArray supplies those ids as field.id.