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

dateRange.tsx

92 lines2.5 KB

1import { defineFieldGroup, useSelector } from '@tanstack/react-form'
2import { FieldError } from '../FieldError'
3import type { FieldWithValue } from '@tanstack/react-form'
4​
5// DateRangeField needs two string fields, but it does not care where they live.
6// These virtual names are the only field names available inside the group.
7// For example, this file can use `start` and `end`, but not `dateRanges[0]`.
8const fieldGroup = defineFieldGroup((helper) => ({
9 start: helper.strict<string>(),
10 end: helper.strict<string>(),
11}))
12​
13interface DateRangeFieldProps {
14 fields: typeof fieldGroup.fields
15 label: string
17​
18function DateRangeFieldComponent(props: DateRangeFieldProps) {
19 const { fields, label } = props
20 // `fields.values` contains only the values declared above, not the entire form.
21 const start = useSelector(fields.atom, (values) => values.start)
22​
23 return (
24 <fieldset>
25 <legend>{label}</legend>
26​
27 {/* The group uses virtual names like `start`; callers provide the real path. */}
28 <fields.Field name="start">
29 {(field) => <DateField field={field} label="Start date" />}
30 </fields.Field>
31​
32 <fields.Field
33 name="end"
34 validators={[
35 {
36 triggers: [
37 {
38 trigger: 'change',
39 when: ({ value }) => Boolean(value && start),
40 },
41 ],
42 // Watched fields are virtual too. This becomes the caller's bound
43 // start path, such as `dateRanges[0].start`.
44 watchFields: ['start'],
45 run: ({ value }) => {
46 if (value < start) {
47 return 'End date must be after the start date'
48 }
49 },
50 },
51 ]}
52 >
53 {(field) => <DateField field={field} label="End date" />}
54 </fields.Field>
55 </fieldset>
56 )
58​
59export const DateRangeField = fieldGroup.bindComponent(
60 DateRangeFieldComponent,
61 'fields',
63​
64interface DateFieldProps {
65 field: FieldWithValue<string>
66 label: string
68​
69function DateField(props: DateFieldProps) {
70 const { field, label } = props
71​
72 return (
73 <label
74 className={field.meta.isValidating ? 'validating' : ''}
75 style={{
76 display: 'block',
77 }}
78 >
79 <span>{label}</span>
80 <input
81 name={field.name}
82 type="date"
83 value={field.value}
84 onBlur={field.handleBlur}
85 onChange={(e) => field.handleChange(e.target.value)}
86 aria-invalid={field.meta.isInvalid}
87 />
88 <br />
89 <FieldError field={field} />
90 </label>
91 )