Open History to see the last commit
1import { useForm } from '@tanstack/preact-form'
2import { render } from 'preact'
3import './index.css'
4import { DateRangeField } from './fieldGroups/dateRange'
5import { LowerBoundField, UpperBoundField } from './fieldGroups/fieldBounds'
6β
7// The bounds field groups package validation and blur normalization once, then
8// each form binds the group's virtual names to its own real field paths.
9function PricingFilterForm() {
10 const form = useForm({
11 defaultValues: {
12 minPrice: '',
13 maxPrice: '',
14 },
15 })
16β
17 return (
18 <>
19 <LowerBoundField
20 label="Lowest Price"
21 form={form}
22 fields={{
23 // The group calls this field `value`; this form stores it at `minPrice`.
24 value: 'minPrice',
25 }}
26 />
27 <UpperBoundField
28 label="Highest Price"
29 form={form}
30 fields={{
31 // `value` is rendered, and `lowerBound` is only read by the validator.
32 value: 'maxPrice',
33 lowerBound: 'minPrice',
34 }}
35 />
36 </>
37 )
38}
39β
40function AgeRangeForm() {
41 const form = useForm({
42 defaultValues: {
43 minAge: '',
44 maxAge: '',
45 },
46 })
47β
48 return (
49 <>
50 <LowerBoundField
51 label="Lowest Age"
52 form={form}
53 fields={{
54 // Same field group, different form paths.
55 value: 'minAge',
56 }}
57 />
58 <UpperBoundField
59 label="Highest Age"
60 form={form}
61 fields={{
62 value: 'maxAge',
63 lowerBound: 'minAge',
64 }}
65 />
66 </>
67 )
68}
69β
70// DateRangeField has access to both dates, but it still knows nothing about the
71// array it is rendered from. The parent form supplies those concrete paths here.
72function SwappableDateRangesForm() {
73 const form = useForm({
74 defaultValues: {
75 dateRanges: [
76 {
77 id: 'A',
78 start: '2026-07-01',
79 end: '2026-07-05',
80 },
81 {
82 id: 'B',
83 start: '2026-08-10',
84 end: '2026-08-15',
85 },
86 ],
87 },
88 })
89β
90 return (
91 <>
92 <button
93 type="button"
94 onClick={() => form.swapFieldValues('dateRanges', 0, 1)}
95 >
96 Swap date ranges
97 </button>
98 <form.ArrayField name="dateRanges">
99 {(array) =>
100 array.value.map((range, i) => (
101 <DateRangeField
102 key={range.id}
103 label={`Range ${range.id}`}
104 form={form}
105 fields={{
106 start: `dateRanges[${i}].start`,
107 end: `dateRanges[${i}].end`,
108 }}
109 />
110 ))
111 }
112 </form.ArrayField>
113 </>
114 )
115}
116β
117function App() {
118 return (
119 <div>
120 <h1>Field Group example</h1>
121β
122 <div>
123 <h2>Price Filter Form</h2>
124 <PricingFilterForm />
125 </div>
126 <div>
127 <h2>Age Range Form</h2>
128 <AgeRangeForm />
129 </div>
130 <div>
131 <h2>Swappable Date Ranges Form</h2>
132 <SwappableDateRangesForm />
133 </div>
134 </div>
135 )
136}
137β
138render(<App />, document.getElementById('root')!)