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

field-groups.md

537 lines15.3 KB

1---
2id: field-groups
3title: Build Reusable React Form Sections with Field Groups
4---
5​
6Related fields often travel together. A scheduling form might need start and end
7times, consistent `HH:mm` formatting, and a rule that prevents the end from
8preceding the start. Another form needs the same behavior, but stores those
9values at different paths.
10​
11A field group makes that component reusable by defining it around the fields it
12needs rather than the shape of a particular parent form. Each form can then bind
13its own field paths to the component.
14​
15This guide assumes you are comfortable creating fields with `useForm`. See the
16[React Quick Start](../quick-start) for that foundation. If you only need to
17move fields from one known form into another file, start with
18[Splitting forms](../../../splitting-forms).
19​
20## A section tied to one form
21​
22Suppose an availability editor stores its times at `availability.opensAt` and
23`availability.closesAt`. A natural first step is to extract those inputs into a
24component that accepts the editor's concrete form type. We can even put the
25blur formatter in that component so its caller does not have to repeat it.
26​
27<!-- ::start:tabs variant="files" -->
28​
29```tsx file="AvailabilityTimeRange.tsx"
30import type { AvailabilityForm } from './form'
31import { TextInput } from './TextInput'
32import { formatTime } from './time-utils'
33​
34function AvailabilityTimeRange({ form }: { form: AvailabilityForm }) {
35 return (
36 <fieldset>
37 <legend>Availability</legend>
38 <form.Field
39 name="availability.opensAt"
40 listeners={[
41 {
42 triggers: ['blur'],
43 run: ({ fieldApi }) => fieldApi.handleChange(formatTime),
44 },
45 ]}
46 >
47 {(field) => <TextInput field={field} label="Opens at" />}
48 </form.Field>
49 <form.Field
50 name="availability.closesAt"
51 listeners={[
52 {
53 triggers: ['blur'],
54 run: ({ fieldApi }) => fieldApi.handleChange(formatTime),
55 },
56 ]}
57 >
58 {(field) => <TextInput field={field} label="Closes at" />}
59 </form.Field>
60 </fieldset>
61 )
63```
64​
65```ts file="form.ts"
66import { formOptions, type ReactFormType } from '@tanstack/react-form'
67​
68export const availabilityFormOptions = formOptions({
69 defaultValues: {
70 availability: {
71 opensAt: '',
72 closesAt: '',
73 },
74 },
75})
76​
77export type AvailabilityForm = ReactFormType<typeof availabilityFormOptions>
78```
79​
80```tsx file="TextInput.tsx"
81import type { FieldWithValue } from '@tanstack/react-form'
82​
83export function TextInput({
84 field,
85 label,
86}: {
87 field: FieldWithValue<string>
88 label: string
89}) {
90 return (
91 <label>
92 {label}
93 <input
94 name={field.name}
95 value={field.value}
96 onBlur={field.handleBlur}
97 onChange={(event) => field.handleChange(event.target.value)}
98 aria-invalid={field.meta.isInvalid}
99 />
100 {field.errors.map((error) => (
101 <small key={error.message} role="alert">
102 {error.message}
103 </small>
104 ))}
105 </label>
106 )
108```
109​
110```ts file="time-utils.ts"
111export function formatTime(value: string) {
112 const match = /^(\d{1,2}):(\d{1,2})$/.exec(value.trim())
113 if (!match) return value
114​
115 const hours = Number(match[1])
116 const minutes = Number(match[2])
117 if (hours > 23 || minutes > 59) return value
118​
119 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
121```
122​
123<!-- ::end:tabs -->
124​
125This is a useful component for the availability editor. It owns the input
126wiring and turns a value such as `9:5` into `09:05` when the field loses focus.
127The limitation appears when a booking form stores the same concept at
128`schedule.departureTime` and `schedule.arrivalTime`. Both the form type and
129the field names tie this component to the availability form.
130​
131We could type `form` as a union of every form that uses the time range,
132but that makes the API difficult to use. It also means constantly fixing
133its type as more forms need it. The time range does not care which form owns the
134values, it only needs certain fields with the declared value types.
135​
136## Define virtual fields
137​
138Let's turn that dependency around. We have fields that need a certain type and depend on each other.
139`defineFieldGroup` lets us define the contract that we expect any given form to complete. Since the fields can come from
140anywhere, the field group can give them virtual names. This time range will call them `start` and `end`.
141​
142The returned definition connects that contract to a React component in two
143steps. Its `fields` value types the field group API that can be used within the component, while `bindComponent`
144creates a callable wrapper that a form can render.
145​
146<!-- ::start:tabs variant="files" -->
147​
148```tsx file="TimeRangeSection.tsx"
149import { defineFieldGroup } from '@tanstack/react-form'
150​
151const timeRangeGroup = defineFieldGroup((helper) => ({
152 // Both virtual fields must bind to concrete fields typed exactly as string.
153 // To only allow the exact type, use `strict`.
154 start: helper.strict<string>(),
155 end: helper.strict<string>(),
156}))
157​
158function TimeRangeFields(_props: {
159 fields: typeof timeRangeGroup.fields
160 label: string
161}) {
162 // ...
163 return null
165​
166export const TimeRangeSection = timeRangeGroup.bindComponent(
167 TimeRangeFields,
168 // The prop that receives the field-group API.
169 'fields',
171```
172​
173<!-- ::end:tabs -->
174​
175The parent form still owns the field values and their default state.
176​
177We will fill in the component body in the next section. For now, its `fields`
178prop is limited to the declared `start` and `end` paths, including their field
179components, methods, and values.
180​
181> [!TIP] Why `bindComponent`?
182> The selected prop keeps its name, but its role changes. Inside the component,
183> it contains the field-group API. At the call site, it contains the
184> virtual-to-concrete field map.
185> `bindComponent` covers both the runtime as well as the types for you.
186​
187## Add field behavior
188​
189Now we can implement formatting and validation against `start` and `end`. The
190blur listeners normalize both values, while the `end` validator watches `start`
191and reports an error when the end precedes it.
192​
193Run the example, enter `9:5` in either field, then move focus away. The value
194becomes `09:05`.
195​
196```tsx group=time-range-field-group env=react file=/App.tsx entry
197import { defineFieldGroup, useForm } from '@tanstack/react-form'
198import { TextInput } from './TextInput'
199import { formatTime, toMinutes } from './time-utils'
200​
201const timeRangeGroup = defineFieldGroup(({ strict }) => ({
202 start: strict<string>(),
203 end: strict<string>(),
204}))
205​
206interface TimeRangeFieldsProps {
207 fields: typeof timeRangeGroup.fields
208 label: string
210​
211function TimeRangeFields({ fields, label }: TimeRangeFieldsProps) {
212 return (
213 <fieldset>
214 <legend>{label}</legend>
215 <fields.Field
216 name="start"
217 listeners={[
218 {
219 triggers: ['blur'],
220 run: () => fields.setFieldValue('start', formatTime),
221 },
222 ]}
223 >
224 {(field) => <TextInput field={field} label="Start time" />}
225 </fields.Field>
226 <fields.Field
227 name="end"
228 validators={[
229 {
230 triggers: ['change', 'blur'],
231 watchFields: ['start'],
232 run: ({ value }) => {
233 const start = toMinutes(fields.getFieldValue('start'))
234 const end = toMinutes(value)
235​
236 if (start !== undefined && end !== undefined && end < start) {
237 return 'End time must not be before the start time'
238 }
239 },
240 },
241 ]}
242 listeners={[
243 {
244 triggers: ['blur'],
245 run: () => fields.setFieldValue('end', formatTime),
246 },
247 ]}
248 >
249 {(field) => <TextInput field={field} label="End time" />}
250 </fields.Field>
251 </fieldset>
252 )
254​
255const TimeRangeSection = timeRangeGroup.bindComponent(TimeRangeFields, 'fields')
256​
257export default function App() {
258 const form = useForm({
259 defaultValues: {
260 availability: {
261 opensAt: '',
262 closesAt: '',
263 },
264 schedule: {
265 departureTime: '08:30',
266 arrivalTime: '10:00',
267 },
268 },
269 })
270​
271 return (
272 <main>
273 <TimeRangeSection
274 form={form}
275 label="Availability"
276 fields={{
277 start: 'availability.opensAt',
278 end: 'availability.closesAt',
279 }}
280 />
281 <TimeRangeSection
282 form={form}
283 label="Travel schedule"
284 fields={{
285 start: 'schedule.departureTime',
286 end: 'schedule.arrivalTime',
287 }}
288 />
289 <form.Subscribe selector={(state) => state.values}>
290 {(values) => (
291 <pre aria-label="Form values">{JSON.stringify(values, null, 2)}</pre>
292 )}
293 </form.Subscribe>
294 </main>
295 )
297```
298​
299```tsx group=time-range-field-group file=/TextInput.tsx collapsed
300import type { FieldWithValue } from '@tanstack/react-form'
301​
302export function TextInput({
303 field,
304 label,
305}: {
306 field: FieldWithValue<string>
307 label: string
308}) {
309 return (
310 <label>
311 {label}
312 <input
313 name={field.name}
314 value={field.value}
315 onBlur={field.handleBlur}
316 onChange={(event) => field.handleChange(event.target.value)}
317 aria-invalid={field.meta.isInvalid}
318 />
319 {field.errors.map((error) => (
320 <small key={error.message} role="alert">
321 {error.message}
322 </small>
323 ))}
324 </label>
325 )
327```
328​
329```ts group=time-range-field-group file=/time-utils.ts collapsed
330export function formatTime(value: string) {
331 const match = /^(\d{1,2}):(\d{1,2})$/.exec(value.trim())
332 if (!match) return value
333​
334 const hours = Number(match[1])
335 const minutes = Number(match[2])
336 if (hours > 23 || minutes > 59) return value
337​
338 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`
340​
341export function toMinutes(value: string) {
342 const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value)
343 if (!match) return undefined
344 return Number(match[1]) * 60 + Number(match[2])
346```
347​
348```json group=time-range-field-group file=/package.json collapsed
350 "dependencies": {
351 "@tanstack/react-form": "2.0.0-alpha.2",
352 "react": "19.2.3",
353 "react-dom": "19.2.3"
354 }
356```
357​
358Both time ranges apply the same formatting and validation even though their
359values use different paths in the parent form.
360​
361## Bind the group to a form
362​
363The `fields` prop maps each virtual field to a concrete path. TypeScript checks
364that every mapping exists and that each destination satisfies its field slot.
365​
366TanStack Form applies the current map to field rendering, field methods,
367validators, listeners, and their `watchFields`. When the end validator watches
368`start`, it therefore resolves the start path for the same time-range instance.
369​
370> [!NOTE] Dynamic paths are allowed
371> Bindings may include array indices and other runtime paths, such as
372> `ranges[${index}].start`.
373​
374The field group remains part of the parent form. It uses the parent's state,
375validation lifecycle, and submission. It does not create a nested form or a
376separate submit boundary.
377​
378### Read field-group values
379​
380The range validator reads the current start time with
381`fields.getFieldValue('start')`. That is a good fit for a value needed only
382while an event is running.
383​
384When rendered output should react to several group values, pass `fields.atom`
385to `useSelector`. The selector stays typed to the virtual fields and does not
386subscribe the component to unrelated form values.
387​
388<!-- ::start:tabs variant="files" -->
389​
390```tsx file="TimeRangeSection.tsx"
391import { useSelector } from '@tanstack/react-form'
392​
393interface TimeRangeSummaryProps {
394 fields: typeof timeRangeGroup.fields
396​
397function TimeRangeSummary({ fields }: TimeRangeSummaryProps) {
398 const start = useSelector(fields.atom, (state) => state.start)
399 const end = useSelector(fields.atom, (state) => state.end)
400​
401 return (
402 <output>
403 {start} to {end}
404 </output>
405 )
407```
408​
409<!-- ::end:tabs -->
410​
411`fields.Subscribe` remains useful for parent form metadata such as submission
412attempts or `isSubmitting`.
413​
414> [!WARNING] Avoid parent form values
415> Parent form values can have any shape. Read values through the field-group
416> API instead. Form metadata remains safe to access.
417​
418### Omit identity mappings
419​
420This binding map adds no information when the parent form already stores
421compatible fields at `start` and `end`.
422​
423<!-- ::start:tabs variant="files" -->
424​
425```tsx file="OfficeHoursForm.tsx"
426<TimeRangeSection
427 form={form}
428 label="Office hours"
429 fields={{
430 start: 'start',
431 end: 'end',
432 }}
433/>
434```
435​
436<!-- ::end:tabs -->
437​
438In this case, omit the `fields` prop. Supply it only to reroute virtual names,
439and include every virtual field when you do.
440​
441### Choose strict or loose bindings
442​
443The time-range group uses `strict<string>()` because its formatter and inputs
444expect ordinary strings. Strict slots accept only concrete fields with exactly
445the declared value type. This catches a surprising binding before the section
446can read or write it.
447​
448Use `loose<T>()` when the concrete field type may be narrower than `T`.
449​
450| Concrete field type | `strict<number \| null>()` | `loose<number \| null>()` |
451| ----------------------------- | -------------------------- | ------------------------- |
452| `number \| null` | βœ“ | βœ“ |
453| `number` | X | βœ“ |
454| `null` | X | βœ“ |
455| `string \| null` | X | X |
456| `number \| null \| undefined` | X | X |
457​
458## Usage in Form Composition
459​
460Since each `createFormHook` can define its own field components, `defineFieldGroup` does not know of them ahead of time.
461If you want to use field components in field groups, use `defineAppFieldGroup` instead. The remaining syntax is exactly the same.
462​
463<!-- ::start:tabs variant="files" -->
464​
465```tsx file="AppTimeRangeSection.tsx"
466import { createFormHook } from '@tanstack/react-form'
467import { TextInput } from './TextInput'
468​
469const { defineAppFieldGroup } = createFormHook({
470 fieldComponents: {
471 TextInput,
472 },
473 formComponents: {},
474})
475​
476const appTimeRangeGroup = defineAppFieldGroup(({ strict }) => ({
477 start: strict<string>(),
478 end: strict<string>(),
479}))
480​
481function AppTimeRangeFields({
482 fields,
483 label,
484}: {
485 fields: typeof appTimeRangeGroup.fields
486 label: string
487}) {
488 return (
489 <fieldset>
490 <legend>{label}</legend>
491 <fields.Field name="start">
492 {(field) => <field.TextInput label="Start time" />}
493 </fields.Field>
494 <fields.Field name="end">
495 {(field) => <field.TextInput label="End time" />}
496 </fields.Field>
497 </fieldset>
498 )
500​
501export const AppTimeRangeSection = appTimeRangeGroup.bindComponent(
502 AppTimeRangeFields,
503 'fields',
505```
506​
507```tsx file="TextInput.tsx"
508import type { FieldWithValue } from '@tanstack/react-form'
509​
510export function TextInput({
511 field,
512 label,
513}: {
514 field: FieldWithValue<string>
515 label: string
516}) {
517 return (
518 <label>
519 {label}
520 <input
521 name={field.name}
522 value={field.value}
523 onBlur={field.handleBlur}
524 onChange={(event) => field.handleChange(event.target.value)}
525 aria-invalid={field.meta.isInvalid}
526 />
527 {field.errors.map((error) => (
528 <small key={error.message} role="alert">
529 {error.message}
530 </small>
531 ))}
532 </label>
533 )
535```
536​
537<!-- ::end:tabs -->