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

index.tsx

125 lines3.5 KB

1/* @refresh reload */
2import { render } from 'solid-js/web'
3​
4import { createForm } from '@tanstack/solid-form'
5import { yupValidator } from '@tanstack/yup-form-adapter'
6import * as yup from 'yup'
7import type { FieldApi } from '@tanstack/solid-form'
8​
9interface FieldInfoProps {
10 field: FieldApi<any, any, any, any>
12​
13function FieldInfo(props: FieldInfoProps) {
14 return (
15 <>
16 {props.field.state.meta.isTouched &&
17 props.field.state.meta.errors.length ? (
18 <em>{props.field.state.meta.errors.join(',')}</em>
19 ) : null}
20 {props.field.state.meta.isValidating ? 'Validating...' : null}
21 </>
22 )
24​
25function App() {
26 const form = createForm(() => ({
27 defaultValues: {
28 firstName: '',
29 lastName: '',
30 },
31 onSubmit: async ({ value }) => {
32 // Do something with form data
33 console.log(value)
34 },
35 // Add a validator to support Yup usage in Form and Field
36 validatorAdapter: yupValidator(),
37 }))
38​
39 return (
40 <div>
41 <h1>Yup Form Example</h1>
42 <form
43 onSubmit={(e) => {
44 e.preventDefault()
45 e.stopPropagation()
46 form.handleSubmit()
47 }}
48 >
49 <div>
50 {/* A type-safe field component*/}
51 <form.Field
52 name="firstName"
53 validators={{
54 onChange: yup
55 .string()
56 .min(3, 'First name must be at least 3 characters'),
57 onChangeAsyncDebounceMs: 500,
58 onChangeAsync: yup
59 .string()
60 .test(
61 'no error',
62 "No 'error' allowed in first name",
63 async (value) => {
64 await new Promise((resolve) => setTimeout(resolve, 1000))
65 return !value?.includes('error')
66 },
67 ),
68 }}
69 children={(field) => {
70 // Avoid hasty abstractions. Render props are great!
71 return (
72 <>
73 <label for={field().name}>First Name:</label>
74 <input
75 id={field().name}
76 name={field().name}
77 value={field().state.value}
78 onBlur={field().handleBlur}
79 onInput={(e) => field().handleChange(e.target.value)}
80 />
81 <FieldInfo field={field()} />
82 </>
83 )
84 }}
85 />
86 </div>
87 <div>
88 <form.Field
89 name="lastName"
90 children={(field) => (
91 <>
92 <label for={field().name}>Last Name:</label>
93 <input
94 id={field().name}
95 name={field().name}
96 value={field().state.value}
97 onBlur={field().handleBlur}
98 onInput={(e) => field().handleChange(e.target.value)}
99 />
100 <FieldInfo field={field()} />
101 </>
102 )}
103 />
104 </div>
105 <form.Subscribe
106 selector={(state) => ({
107 canSubmit: state.canSubmit,
108 isSubmitting: state.isSubmitting,
109 })}
110 children={(state) => {
111 return (
112 <button type="submit" disabled={!state().canSubmit}>
113 {state().isSubmitting ? '...' : 'Submit'}
114 </button>
115 )
116 }}
117 />
118 </form>
119 </div>
120 )
122​
123const root = document.getElementById('root')
124​
125render(() => <App />, root!)