Skip to content

Array Fields

TanStack Form fields can work with both simple and complex types. Arrays are no exception. For example, you might have a multi-select menu to add tags to an article:

EditArticleForm.tsx
import { useForm } from '@tanstack/react-form'
import { TagSelector } from './UI'
import type { ArticleTags } from './UI'

export default function EditArticleForm() {
  const form = useForm({
    defaultValues: {
      tags: [] as ArticleTags[],
    },
  })

  return (
    <form.Field name="tags">
      {(field) => (
        <>
          <label htmlFor={field.name}>Tags</label>
          <TagSelector
            name={field.name}
            selected={field.value}
            onSelectedChange={field.handleChange}
          />
        </>
      )}
    </form.Field>
  )
}

Updating array values

Helper methods are also available to make some array updates easier:

ts
// Use the updater function if the new array is based on the old one
field.handleChange((previousTags) => toggleItem(previousTags, 'Business'))

field.pushValue('Business')
field.insertValue(index, 'Business')
field.replaceValue(index, 'Business')
field.removeValue(index)
field.swapValues(indexA, indexB)
field.moveValue(fromIndex, toIndex)
field.filterValues((tag) => tag !== 'Travel')
field.clearValues()

Edit each item separately

Not all array fields are that straightforward, though. For example, we might have a list of guests for a booking. We can add and remove guests, but we can also edit each guest's name.

You might start by rendering a field for each guest's name. However, this causes more rerenders than necessary:

GuestList.tsx
import { Fragment } from 'react'
import { useForm } from '@tanstack/react-form'
import { TextInput } from './UI'

export default function GuestList() {
  const form = useForm({
    defaultValues: {
      guests: [{ id: 'guest-1', name: 'Guest 1' }],
    },
  })

  function addGuest() {
    form.pushFieldValue('guests', { id: crypto.randomUUID(), name: '' })
  }

  return (
    <form.Field name="guests">
      {(guestsField) => (
        <>
          {/*
            Changing ANY guest's name rerenders the whole array
            because the array's value is updated
          */}
          {guestsField.value.map((guest, i) => (
            <Fragment key={guest.id}>
              <form.Field name={`guests[${i}].name`}>
                {(field) => <TextInput label="Name" field={field} />}
              </form.Field>

              <button type="button" onClick={() => guestsField.removeValue(i)}>
                Remove
              </button>
            </Fragment>
          ))}
          <button type="button" onClick={addGuest}>
            Add Guest
          </button>
        </>
      )}
    </form.Field>
  )
}

That's where form.ArrayField comes in:

An array of fields with ArrayField

<form.ArrayField /> works much like a normal <form.Field />. It's still a field, but its rerender behavior differs:

ChangesFieldArrayField
Field's value changesβœ…πŸ›‘
Field's meta changesβœ…πŸ›‘ by default
Array length changesβœ…βœ…
field.pushValue and other array methodsβœ…βœ…

To avoid these extra rerenders, change the array's form.Field to a form.ArrayField:

GuestList.tsx
import { Fragment } from 'react'
import { useForm } from '@tanstack/react-form'
import { TextInput } from './UI'

export default function GuestList() {
  const form = useForm({
    defaultValues: {
      guests: [{ id: 'guest-1', name: 'Guest 1' }],
    },
  })

  function addGuest() {
    form.pushFieldValue('guests', { id: crypto.randomUUID(), name: '' })
  }

  return (
    <form.ArrayField name="guests">
      {(guestsField) => (
        <>
          {/* Changing guest names do not rerender the array now */}
          {guestsField.value.map((guest, i) => (
            <Fragment key={guest.id}>
              <form.Field name={`guests[${i}].name`}>
                {(field) => <TextInput label="Name" field={field} />}
              </form.Field>
              <button type="button" onClick={() => guestsField.removeValue(i)}>
                Remove
              </button>
            </Fragment>
          ))}
          <button type="button" onClick={addGuest}>
            Add Guest
          </button>
        </>
      )}
    </form.ArrayField>
  )
}

Changing elements in the array

When removing, adding, or moving items in the array, use the helper methods listed in Updating array values. These let form.ArrayField know that a rerender is needed. Using field.handleChange directly can leave stale items.

diff
- arrayField.handleChange(array => array.filter(item => item !== 'Item'))
+ arrayField.filterValues(item => item !== 'Item')

Reading meta from ArrayField

Most uses of form.ArrayField focus on individual items. To avoid unnecessary rerenders, form.ArrayField ignores changes to its own meta by default. If you want to render the array field's meta properties, such as field.errors or field.meta.isTouched, enable the subscribeToMeta flag:

tsx
// ...
<form.ArrayField name="guests" subscribeToMeta>
  {(field) => {
    /* ... */
    return null
  }}
</form.ArrayField>