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

index.tsx

110 lines3.4 KB

1import * as React from 'react'
2import { createRoot } from 'react-dom/client'
3import { useForm } from '@tanstack/react-form'
4import { valibotValidator } from '@tanstack/valibot-form-adapter'
5import { customAsync, minLength, string, stringAsync } from 'valibot'
6import type { FieldApi } from '@tanstack/react-form'
7​
8function FieldInfo({ field }: { field: FieldApi<any, any, any, any> }) {
9 return (
10 <>
11 {field.state.meta.touchedErrors ? (
12 <em>{field.state.meta.touchedErrors}</em>
13 ) : null}
14 {field.state.meta.isValidating ? 'Validating...' : null}
15 </>
16 )
18​
19export default function App() {
20 const form = useForm({
21 defaultValues: {
22 firstName: '',
23 lastName: '',
24 },
25 onSubmit: async ({ value }) => {
26 // Do something with form data
27 console.log(value)
28 },
29 // Add a validator to support Valibot usage in Form and Field
30 validatorAdapter: valibotValidator,
31 })
32​
33 return (
34 <div>
35 <h1>Valibot Form Example</h1>
36 <form.Provider>
37 <form
38 onSubmit={(e) => {
39 e.preventDefault()
40 e.stopPropagation()
41 void form.handleSubmit()
42 }}
43 >
44 <div>
45 {/* A type-safe field component*/}
46 <form.Field
47 name="firstName"
48 validators={{
49 onChange: string([
50 minLength(3, 'First name must be at least 3 characters'),
51 ]),
52 onChangeAsyncDebounceMs: 500,
53 onChangeAsync: stringAsync([
54 customAsync(async (value) => {
55 await new Promise((resolve) => setTimeout(resolve, 1000))
56 return !value.includes('error')
57 }, "No 'error' allowed in first name"),
58 ]),
59 }}
60 children={(field) => {
61 // Avoid hasty abstractions. Render props are great!
62 return (
63 <>
64 <label htmlFor={field.name}>First Name:</label>
65 <input
66 name={field.name}
67 value={field.state.value}
68 onBlur={field.handleBlur}
69 onChange={(e) => field.handleChange(e.target.value)}
70 />
71 <FieldInfo field={field} />
72 </>
73 )
74 }}
75 />
76 </div>
77 <div>
78 <form.Field
79 name="lastName"
80 children={(field) => (
81 <>
82 <label htmlFor={field.name}>Last Name:</label>
83 <input
84 name={field.name}
85 value={field.state.value}
86 onBlur={field.handleBlur}
87 onChange={(e) => field.handleChange(e.target.value)}
88 />
89 <FieldInfo field={field} />
90 </>
91 )}
92 />
93 </div>
94 <form.Subscribe
95 selector={(state) => [state.canSubmit, state.isSubmitting]}
96 children={([canSubmit, isSubmitting]) => (
97 <button type="submit" disabled={!canSubmit}>
98 {isSubmitting ? '...' : 'Submit'}
99 </button>
100 )}
101 />
102 </form>
103 </form.Provider>
104 </div>
105 )
107​
108const rootElement = document.getElementById('root')!
109​
110createRoot(rootElement).render(<App />)