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

index.tsx

115 lines2.9 KB

1import { render } from 'preact'
2​
3import { useForm } from '@tanstack/preact-form'
4​
5import type { AnyFieldApi } from '@tanstack/preact-form'
6​
7function FieldInfo({ field }: { field: AnyFieldApi }) {
8 return (
9 <>
10 {field.state.meta.isTouched && !field.state.meta.isValid ? (
11 <em>{field.state.meta.errors.join(',')}</em>
12 ) : null}
13 {field.state.meta.isValidating ? 'Validating...' : null}
14 </>
15 )
17​
18function App() {
19 const form = useForm({
20 defaultValues: {
21 firstName: '',
22 lastName: '',
23 },
24 onSubmit: async ({ value }) => {
25 console.log(value)
26 },
27 })
28​
29 return (
30 <div>
31 <h1>Simple Preact Form Example</h1>
32 <form
33 onSubmit={(e) => {
34 e.preventDefault()
35 e.stopPropagation()
36 void form.handleSubmit()
37 }}
38 >
39 <div>
40 <form.Field
41 name="firstName"
42 validators={{
43 onChange: ({ value }) =>
44 !value
45 ? 'A first name is required'
46 : value.length < 3
47 ? 'First name must be at least 3 characters'
48 : undefined,
49 }}
50 children={(field) => (
51 <>
52 <label htmlFor={field.name}>First Name:</label>
53 <input
54 id={field.name}
55 name={field.name}
56 value={field.state.value}
57 onBlur={field.handleBlur}
58 onInput={(e) => field.handleChange(e.currentTarget.value)}
59 />
60 <FieldInfo field={field} />
61 </>
62 )}
63 />
64 </div>
65​
66 <div>
67 <form.Field
68 name="lastName"
69 children={(field) => (
70 <>
71 <label htmlFor={field.name}>Last Name:</label>
72 <input
73 id={field.name}
74 name={field.name}
75 value={field.state.value}
76 onBlur={field.handleBlur}
77 onInput={(e) => field.handleChange(e.currentTarget.value)}
78 />
79 <FieldInfo field={field} />
80 </>
81 )}
82 />
83 </div>
84​
85 <form.Subscribe
86 selector={(state) => [state.canSubmit, state.isSubmitting]}
87 children={([canSubmit, isSubmitting]) => (
88 <>
89 <button type="submit" disabled={!canSubmit}>
90 {isSubmitting ? '...' : 'Submit'}
91 </button>
92 <button
93 type="reset"
94 onClick={(e) => {
95 e.preventDefault()
96 form.reset()
97 }}
98 >
99 Reset
100 </button>
101 </>
102 )}
103 />
104 </form>
105 </div>
106 )
108​
109const rootElement = document.getElementById('root')
110​
111if (!rootElement) {
112 throw new Error('Root element not found')
114​
115render(<App />, rootElement)