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

index.tsx

161 lines4.2 KB

1import * as React from 'react'
2import { createRoot } from 'react-dom/client'
3​
4import { type } from 'arktype'
5import { Schema as S } from 'effect'
6import * as v from 'valibot'
7import { z } from 'zod'
8​
9import { TanStackDevtools } from '@tanstack/react-devtools'
10import { formDevtoolsPlugin } from '@tanstack/react-form-devtools'
11import { useForm } from '@tanstack/react-form'
12​
13import type { AnyFieldApi } from '@tanstack/react-form'
14​
15function FieldInfo({ field }: { field: AnyFieldApi }) {
16 return (
17 <>
18 {field.state.meta.isTouched && !field.state.meta.isValid ? (
19 <em>{field.state.meta.errors.map((err) => err.message).join(',')}</em>
20 ) : null}
21 {field.state.meta.isValidating ? 'Validating...' : null}
22 </>
23 )
25​
26const ZodSchema = z.object({
27 firstName: z
28 .string()
29 .min(3, '[Zod] You must have a length of at least 3')
30 .startsWith('A', "[Zod] First name must start with 'A'"),
31 lastName: z.string().min(3, '[Zod] You must have a length of at least 3'),
32})
33​
34const ValibotSchema = v.object({
35 firstName: v.pipe(
36 v.string(),
37 v.minLength(3, '[Valibot] You must have a length of at least 3'),
38 v.startsWith('A', "[Valibot] First name must start with 'A'"),
39 ),
40 lastName: v.pipe(
41 v.string(),
42 v.minLength(3, '[Valibot] You must have a length of at least 3'),
43 ),
44})
45​
46const ArkTypeSchema = type({
47 firstName: 'string >= 3',
48 lastName: 'string >= 3',
49})
50​
51const EffectSchema = S.standardSchemaV1(
52 S.Struct({
53 firstName: S.String.pipe(
54 S.minLength(3),
55 S.annotations({
56 message: () => '[Effect/Schema] You must have a length of at least 3',
57 }),
58 ),
59 lastName: S.String.pipe(
60 S.minLength(3),
61 S.annotations({
62 message: () => '[Effect/Schema] You must have a length of at least 3',
63 }),
64 ),
65 }),
67​
68export default function App() {
69 const form = useForm({
70 defaultValues: {
71 firstName: '',
72 lastName: '',
73 },
74 validators: {
75 // DEMO: You can switch between schemas seamlessly
76 onChange: ZodSchema,
77 // onChange: ValibotSchema,
78 // onChange: ArkTypeSchema,
79 // onChange: EffectSchema,
80 },
81 onSubmit: async ({ value }) => {
82 // Do something with form data
83 console.log(value)
84 },
85 })
86​
87 return (
88 <div>
89 <h1>Standard Schema Form Example</h1>
90 <form
91 onSubmit={(e) => {
92 e.preventDefault()
93 e.stopPropagation()
94 form.handleSubmit()
95 }}
96 >
97 <div>
98 {/* A type-safe field component*/}
99 <form.Field
100 name="firstName"
101 children={(field) => {
102 // Avoid hasty abstractions. Render props are great!
103 return (
104 <>
105 <label htmlFor={field.name}>First Name:</label>
106 <input
107 id={field.name}
108 name={field.name}
109 value={field.state.value}
110 onBlur={field.handleBlur}
111 onChange={(e) => field.handleChange(e.target.value)}
112 />
113 <FieldInfo field={field} />
114 </>
115 )
116 }}
117 />
118 </div>
119 <div>
120 <form.Field
121 name="lastName"
122 children={(field) => (
123 <>
124 <label htmlFor={field.name}>Last Name:</label>
125 <input
126 id={field.name}
127 name={field.name}
128 value={field.state.value}
129 onBlur={field.handleBlur}
130 onChange={(e) => field.handleChange(e.target.value)}
131 />
132 <FieldInfo field={field} />
133 </>
134 )}
135 />
136 </div>
137 <form.Subscribe
138 selector={(state) => [state.canSubmit, state.isSubmitting]}
139 children={([canSubmit, isSubmitting]) => (
140 <button type="submit" disabled={!canSubmit}>
141 {isSubmitting ? '...' : 'Submit'}
142 </button>
143 )}
144 />
145 </form>
146 </div>
147 )
149​
150const rootElement = document.getElementById('root')!
151​
152createRoot(rootElement).render(
153 <React.StrictMode>
154 <App />
155​
156 <TanStackDevtools
157 config={{ hideUntilHover: true }}
158 plugins={[formDevtoolsPlugin()]}
159 />
160 </React.StrictMode>,