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