Open History to see the last commit
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 )
62}
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 )
107}
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')}`
120}
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
164}
165β
166export const TimeRangeSection = timeRangeGroup.bindComponent(
167 TimeRangeFields,
168 // The prop that receives the field-group API.
169 'fields',
170)
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
209}
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 )
253}
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 )
296}
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 )
326}
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')}`
339}
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])
345}
346```
347β
348```json group=time-range-field-group file=/package.json collapsed
349{
350 "dependencies": {
351 "@tanstack/react-form": "2.0.0-alpha.2",
352 "react": "19.2.3",
353 "react-dom": "19.2.3"
354 }
355}
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
395}
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 )
406}
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 )
499}
500β
501export const AppTimeRangeSection = appTimeRangeGroup.bindComponent(
502 AppTimeRangeFields,
503 'fields',
504)
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 )
534}
535```
536β
537<!-- ::end:tabs -->