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

index.tsx

114 lines3.4 KB

1import * as React from 'react'
2import { createRoot } from 'react-dom/client'
3import { useForm } from '@tanstack/react-form'
4import { yupValidator } from '@tanstack/yup-form-adapter'
5import * as yup from 'yup'
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 Yup usage in Form and Field
30 validatorAdapter: yupValidator,
31 })
32​
33 return (
34 <div>
35 <h1>Yup 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: yup
50 .string()
51 .min(3, 'First name must be at least 3 characters'),
52 onChangeAsyncDebounceMs: 500,
53 onChangeAsync: yup
54 .string()
55 .test(
56 'no error',
57 "No 'error' allowed in first name",
58 async (value) => {
59 await new Promise((resolve) => setTimeout(resolve, 1000))
60 return !value?.includes('error')
61 },
62 ),
63 }}
64 children={(field) => {
65 // Avoid hasty abstractions. Render props are great!
66 return (
67 <>
68 <label htmlFor={field.name}>First Name:</label>
69 <input
70 name={field.name}
71 value={field.state.value}
72 onBlur={field.handleBlur}
73 onChange={(e) => field.handleChange(e.target.value)}
74 />
75 <FieldInfo field={field} />
76 </>
77 )
78 }}
79 />
80 </div>
81 <div>
82 <form.Field
83 name="lastName"
84 children={(field) => (
85 <>
86 <label htmlFor={field.name}>Last Name:</label>
87 <input
88 name={field.name}
89 value={field.state.value}
90 onBlur={field.handleBlur}
91 onChange={(e) => field.handleChange(e.target.value)}
92 />
93 <FieldInfo field={field} />
94 </>
95 )}
96 />
97 </div>
98 <form.Subscribe
99 selector={(state) => [state.canSubmit, state.isSubmitting]}
100 children={([canSubmit, isSubmitting]) => (
101 <button type="submit" disabled={!canSubmit}>
102 {isSubmitting ? '...' : 'Submit'}
103 </button>
104 )}
105 />
106 </form>
107 </form.Provider>
108 </div>
109 )
111​
112const rootElement = document.getElementById('root')!
113​
114createRoot(rootElement).render(<App />)