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:
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>
)
}import type { ChangeEvent } from 'react'
// This file provides the UI. Use any UI library you prefer.
const availableTags = ['Travel', 'Science', 'Business', 'Politics' /* ... */]
export type ArticleTags = (typeof availableTags)[number]
function TagOptions() {
return availableTags.map((tag) => (
<option key={tag} value={tag}>
{tag}
</option>
))
}
interface TagSelectorProps {
name: string
selected: ArticleTags[]
onSelectedChange: (value: ArticleTags[]) => void
}
export function TagSelector(props: TagSelectorProps) {
function handleChange(event: ChangeEvent<HTMLSelectElement>) {
const newChoices = Array.from(
event.target.selectedOptions,
(option) => option.value,
)
props.onSelectedChange(newChoices as ArticleTags[])
}
return (
<select
multiple
id={props.name}
name={props.name}
value={props.selected}
onChange={handleChange}
>
<TagOptions />
</select>
)
}Updating array values#
Helper methods are also available to make some array updates easier:
// 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:
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>
)
}import type { FieldWithValue } from '@tanstack/react-form'
// This file provides the UI. Use any UI library you prefer.
export function TextInput({
field,
label,
}: {
field: FieldWithValue<string>
label: string
}) {
return (
<label>
{label}
<input
type="text"
name={field.name}
value={field.value}
onBlur={field.handleBlur}
onChange={(event) => field.handleChange(event.target.value)}
/>
</label>
)
}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:
| Changes | Field | ArrayField |
|---|---|---|
| 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:
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>
)
}import type { FieldWithValue } from '@tanstack/react-form'
// This file provides the UI. Use any UI library you prefer.
export function TextInput({
field,
label,
}: {
field: FieldWithValue<string>
label: string
}) {
return (
<label>
{label}
<input
type="text"
name={field.name}
value={field.value}
onBlur={field.handleBlur}
onChange={(event) => field.handleChange(event.target.value)}
/>
</label>
)
}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.
- 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:
// ...
<form.ArrayField name="guests" subscribeToMeta>
{(field) => {
/* ... */
return null
}}
</form.ArrayField>