Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

arrays.md

429 lines9.6 KB

1---
2id: arrays
3title: Arrays
4---
5​
6TanStack Form fields can hold arrays just like any other value. The important distinction is whether the array is the field value itself or whether you're rendering fields for the items inside it.
7​
8If one control reads and replaces the whole array, use a regular field. If you're rendering fields for individual items and need to add, remove, or reorder them, use an array field.
9​
10This guide covers both cases and how to choose between them.
11​
12## An array as the field value
13​
14Use a regular field when one control reads and replaces the complete array. A
15multi-select, tag picker, or checkbox group can pass its next array to
16`handleChange` like any other field value:
17​
18<!-- ::start:framework -->
19​
20# React
21​
22```tsx
23<form.Field name="selectedRoleIds">
24 {(field) => (
25 <RolePicker
26 value={field.value}
27 onValueChange={(roleIds) => field.handleChange(roleIds)}
28 />
29 )}
30</form.Field>
31```
32​
33# Preact
34​
35```tsx
36<form.Field name="selectedRoleIds">
37 {(field) => (
38 <RolePicker
39 value={field.value}
40 onValueChange={(roleIds) => field.handleChange(roleIds)}
41 />
42 )}
43</form.Field>
44```
45​
46# Solid
47​
48```tsx
49<form.Field name="selectedRoleIds">
50 {(field) => (
51 <RolePicker
52 value={field().value}
53 onValueChange={(roleIds) => field().handleChange(roleIds)}
54 />
55 )}
56</form.Field>
57```
58​
59# Angular
60​
61```html
62<ng-container [tanstackField]="form" name="selectedRoleIds" #field="field">
63 <app-role-picker
64 [value]="field.api.value"
65 (valueChange)="field.api.handleChange($event)"
66 />
67</ng-container>
68```
69​
70# Lit
71​
72```ts
73this.form.field(
74 { name: 'selectedRoleIds' },
75 (field) => html`
76 <role-picker
77 .value=${field.value}
78 @value-change=${(event: CustomEvent<Array<string>>) =>
79 field.handleChange(event.detail)}
80 ></role-picker>
81 `,
83```
84​
85# Svelte
86​
87```svelte
88<form.Field name="selectedRoleIds">
89 {#snippet children(field)}
90 <RolePicker
91 value={field.value}
92 onValueChange={(roleIds) => field.handleChange(roleIds)}
93 />
94 {/snippet}
95</form.Field>
96```
97​
98# Vue
99​
100```vue
101<form.Field name="selectedRoleIds" v-slot="{ field }">
102 <RolePicker
103 :model-value="field.value"
104 @update:model-value="field.handleChange"
105 />
106</form.Field>
107```
108​
109<!-- ::end:framework -->
110​
111## Rendering fields in an array
112​
113If you need to edit fields inside each array item, the previous approach has two problems.
114​
115- Editing any item's value would cause the whole array to rerender.
116- Moving items within the array would not update fields, since it was only changing the array's value.
117​
118<!-- ::start:framework -->
119​
120# React
121​
122This is where `form.ArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
123item changes like swapping, removing or pushing new values.
124​
125```tsx
126<form.ArrayField name="people">
127 {(array) => (
128 <ul>
129 {array.value.map((person, index) => (
130 <li key={person.id}>
131 <form.Field name={`people[${index}].name`}>
132 {(field) => <TextInput field={field} />}
133 </form.Field>
134 </li>
135 ))}
136 </ul>
137 )}
138</form.ArrayField>
139```
140​
141# Preact
142​
143This is where `form.ArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
144item changes like swapping, removing or pushing new values.
145​
146```tsx
147<form.ArrayField name="people">
148 {(array) => (
149 <ul>
150 {array.value.map((person, index) => (
151 <li key={person.id}>
152 <form.Field name={`people[${index}].name`}>
153 {(field) => <TextInput field={field} />}
154 </form.Field>
155 </li>
156 ))}
157 </ul>
158 )}
159</form.ArrayField>
160```
161​
162# Solid
163​
164This is where `form.ArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
165item changes like swapping, removing or pushing new values.
166​
167```tsx
168<form.ArrayField name="people">
169 {(array) => (
170 <ul>
171 <For each={array().value}>
172 {(_person, index) => (
173 <li>
174 <form.Field name={`people[${index()}].name`}>
175 {(field) => <TextInput field={field} />}
176 </form.Field>
177 </li>
178 )}
179 </For>
180 </ul>
181 )}
182</form.ArrayField>
183```
184​
185# Angular
186​
187This is where `TanStackArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
188item changes like swapping, removing or pushing new values.
189​
190```ts
191import { Component } from '@angular/core'
192import {
193 TanStackArrayField,
194 TanStackField,
195 injectForm,
196} from '@tanstack/angular-form'
197​
198@Component({
199 selector: 'app-people-form',
200 standalone: true,
201 imports: [TanStackArrayField, TanStackField],
202 template: `
203 <ng-container
204 [tanstackArrayField]="form"
205 name="people"
206 #people="arrayField"
207 >
208 <ul>
209 @for (person of people.api.value; track person.id; let index = $index) {
210 <li>
211 <ng-container
212 [tanstackField]="form"
213 [name]="personName(index)"
214 #field="field"
215 >
216 <app-text-input [field]="field.api" />
217 </ng-container>
218 </li>
219 }
220 </ul>
221 </ng-container>
222 `,
223})
224export class PeopleFormComponent {
225 form = injectForm({
226 defaultValues: {
227 people: [{ id: 'person-1', name: '' }],
228 },
229 })
230​
231 personName(index: number): `people[${number}].name` {
232 return `people[${index}].name`
233 }
235```
236​
237# Lit
238​
239This is where `form.arrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
240item changes like swapping, removing or pushing new values.
241​
242```ts
243this.form.arrayField(
244 { name: 'people' },
245 (array) => html`
246 <ul>
247 ${repeat(
248 array.value,
249 (person) => person.id,
250 (_person, index) => html`
251 <li>
252 ${this.form.field(
253 { name: `people[${index}].name` },
254 (field) => html`<text-input .field=${field}></text-input>`,
255 )}
256 </li>
257 `,
258 )}
259 </ul>
260 `,
262```
263​
264# Svelte
265​
266This is where `form.ArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
267item changes like swapping, removing or pushing new values.
268​
269```svelte
270<form.ArrayField name="people">
271 {#snippet children(array)}
272 <ul>
273 {#each array.value as person, index (person.id)}
274 <li>
275 <form.Field name={`people[${index}].name`}>
276 {#snippet children(field)}
277 <TextInput field={field} />
278 {/snippet}
279 </form.Field>
280 </li>
281 {/each}
282 </ul>
283 {/snippet}
284</form.ArrayField>
285```
286​
287# Vue
288​
289This is where `form.ArrayField` comes in. It ensures that each item in the array is rendered independently, while still subscribing to
290item changes like swapping, removing or pushing new values.
291​
292```vue
293<form.ArrayField name="people" v-slot="{ field: array }">
294 <ul>
295 <li v-for="(person, index) in array.value" :key="person.id">
296 <form.Field :name="`people[${index}].name`" v-slot="{ field }">
297 <TextInput :field="field" />
298 </form.Field>
299 </li>
300 </ul>
301</form.ArrayField>
302```
303​
304<!-- ::end:framework -->
305​
306### Keeping item identity for objects
307​
308While the nested fields use the index in their `name`, use your adapter's identity mechanism to keep each object tied
309to the same rendered item.
310​
311<!-- ::start:framework -->
312​
313# React
314​
315```tsx
316array.value.map((person) => <li key={person.id}>Item fields</li>)
317```
318​
319# Preact
320​
321```tsx
322array.value.map((person) => <li key={person.id}>Item fields</li>)
323```
324​
325# Solid
326​
327```tsx
328<For each={array().value}>{() => <li>Item fields</li>}</For>
329```
330​
331# Angular
332​
333```html
334@for (person of people.api.value; track person.id) {
335<li>Item fields</li>
337```
338​
339# Lit
340​
341```ts
342repeat(
343 array.value,
344 (person) => person.id,
345 () => html`<li>Item fields</li>`,
347```
348​
349# Svelte
350​
351```svelte
352{#each array.value as person (person.id)}
353 <li>Item fields</li>
354{/each}
355```
356​
357# Vue
358​
359```vue
360<li v-for="person in array.value" :key="person.id">Item fields</li>
361```
362​
363<!-- ::end:framework -->
364​
365## Updating array values
366​
367Use the array field's mutation methods for structural changes. You can perform the same mutations from the form API by
368passing the field name first.
369​
370<!-- ::start:tabs variant="files" -->
371​
372```ts file="Field methods"
373// Append an item.
374field.pushValue(value)
375​
376// Insert an item at an index.
377field.insertValue(index, value)
378​
379// Remove the item at an index.
380field.removeValue(index)
381​
382// Replace the item at an index.
383field.replaceValue(index, value)
384​
385// Exchange two items.
386field.swapValues(indexA, indexB)
387​
388// Move an item from one index to another.
389field.moveValue(fromIndex, toIndex)
390​
391// Keep the items accepted by a predicate.
392field.filterValues((value, i) => isEnabled(value))
393​
394// Remove every item.
395field.clearValues()
396```
397​
398```ts file="Form methods"
399// Append an item.
400form.pushFieldValue('items', value)
401​
402// Insert an item at an index.
403form.insertFieldValue('items', index, value)
404​
405// Remove the item at an index.
406form.removeFieldValue('items', index)
407​
408// Replace the item at an index.
409form.replaceFieldValue('items', index, value)
410​
411// Exchange two items.
412form.swapFieldValues('items', indexA, indexB)
413​
414// Move an item from one index to another.
415form.moveFieldValue('items', fromIndex, toIndex)
416​
417// Keep the items accepted by a predicate.
418form.filterFieldValues('items', (value, i) => isEnabled(value))
419​
420// Remove every item.
421form.clearFieldValues('items')
422```
423​
424<!-- ::end:tabs -->
425​
426You could make these changes yourself with `handleChange`, but these helpers also take care of the registered fields
427for each item. When an item moves, its field state moves with it. When an item is removed, its field state is removed too.
428​
429A successful array mutation marks the array field as touched and dirty and causes validation by default.