-
-
Notifications
You must be signed in to change notification settings - Fork 345
/
index.tsx
97 lines (92 loc) · 2.86 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import React from "react";
import ReactDOM from "react-dom/client";
import { useForm } from "@tanstack/react-form";
import type { FieldApi } from "@tanstack/react-form";
function FieldInfo({ field }: { field: FieldApi<any, any> }) {
return (
<>
{field.state.meta.touchedError ? (
<em>{field.state.meta.touchedError}</em>
) : null}{" "}
{field.state.meta.isValidating ? "Validating..." : null}
</>
);
}
export default function App() {
const form = useForm({
// Memoize your default values to prevent re-renders
defaultValues: React.useMemo(
() => ({
firstName: "",
lastName: "",
}),
[],
),
onSubmit: async (values) => {
// Do something with form data
console.log(values);
},
});
return (
<div>
<h1>Simple Form Example</h1>
{/* A pre-bound form component */}
<form.Provider>
<form {...form.getFormProps()}>
<div>
{/* A type-safe and pre-bound field component*/}
<form.Field
name="firstName"
onChange={(value) =>
!value
? "A first name is required"
: value.length < 3
? "First name must be at least 3 characters"
: undefined
}
onChangeAsyncDebounceMs={500}
onChangeAsync={async (value) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
return (
value.includes("error") && 'No "error" allowed in first name'
);
}}
children={(field) => {
// Avoid hasty abstractions. Render props are great!
return (
<>
<label htmlFor={field.name}>First Name:</label>
<input name={field.name} {...field.getInputProps()} />
<FieldInfo field={field} />
</>
);
}}
/>
</div>
<div>
<form.Field
name="lastName"
children={(field) => (
<>
<label htmlFor={field.name}>Last Name:</label>
<input name={field.name} {...field.getInputProps()} />
<FieldInfo field={field} />
</>
)}
/>
</div>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
children={([canSubmit, isSubmitting]) => (
<button type="submit" disabled={!canSubmit}>
{isSubmitting ? "..." : "Submit"}
</button>
)}
/>
</form>
</form.Provider>
</div>
);
}
const rootElement = document.getElementById("root")!;
ReactDOM.createRoot(rootElement).render(<App />);