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

index.tsx

132 lines3.5 KB

1import * as React from 'react'
2import { createRoot } from 'react-dom/client'
3import { useForm } from '@tanstack/react-form'
4import type {
5 DeepKeyValueName,
6 FieldOptions,
7 ReactFormApi,
8} from '@tanstack/react-form'
9​
10/**
11 * Export these components to your design system or a dedicated component location
12 */
13interface TextInputFieldProps<
14 TFormData extends unknown,
15 TName extends DeepKeyValueName<TFormData, string>,
16> extends FieldOptions<TFormData, TName> {
17 form: ReactFormApi<TFormData, any>
18 // Your custom props
19 label: string
21​
22function TextInputField<
23 TFormData extends unknown,
24 TName extends DeepKeyValueName<TFormData, string>,
25>({ form, name, label, ...fieldProps }: TextInputFieldProps<TFormData, TName>) {
26 return (
27 // Manually type-cast form.Field to work around this issue:
28 // https://twitter.com/crutchcorn/status/1809827621485900049
29 <form.Field<TName, any, any>
30 {...fieldProps}
31 name={name}
32 children={(field) => {
33 return (
34 <div style={{ marginBottom: '1rem' }}>
35 <div>
36 <label htmlFor={field.name}>{label}</label>
37 </div>
38 <input
39 id={field.name}
40 name={field.name}
41 value={field.state.value}
42 onBlur={field.handleBlur}
43 onChange={(e) => field.handleChange(e.target.value)}
44 />
45 {field.state.meta.isValidating ? (
46 <div style={{ color: 'gray' }}>Validating...</div>
47 ) : null}
48 {field.state.meta.isTouched && field.state.meta.errors.length ? (
49 <div style={{ color: 'red' }}>
50 {field.state.meta.errors.join(', ')}
51 </div>
52 ) : null}
53 </div>
54 )
55 }}
56 />
57 )
59​
60function SubmitButton({ form }: { form: ReactFormApi<any, any> }) {
61 return (
62 <form.Subscribe
63 selector={(state) => [state.canSubmit, state.isSubmitting]}
64 children={([canSubmit, isSubmitting]) => (
65 <>
66 <button type="submit" disabled={!canSubmit}>
67 {isSubmitting ? '...' : 'Submit'}
68 </button>
69 </>
70 )}
71 />
72 )
74​
75/**
76 * Then use it in your application
77 */
78export default function App() {
79 const form = useForm({
80 defaultValues: {
81 firstName: '',
82 age: 0,
83 },
84 onSubmit: async ({ value }) => {
85 // Do something with form data
86 console.log(value)
87 },
88 })
89​
90 return (
91 <div>
92 <h1>Wrapped Fields Form Example</h1>
93 <form
94 onSubmit={(e) => {
95 e.preventDefault()
96 e.stopPropagation()
97 form.handleSubmit()
98 }}
99 >
100 {/* A type-safe, wrapped field component*/}
101 <TextInputField
102 label={'First name:'}
103 form={form}
104 name="firstName"
105 validators={{
106 onChangeAsync: async ({ value }) => {
107 await new Promise((resolve) => setTimeout(resolve, 1000))
108 if (value.length < 3) {
109 return 'Name must be at least 3 characters long'
110 }
111 return undefined
112 },
113 }}
114 />
115 {/* Correctly throws a warning when the wrong data type is passed */}
116 <TextInputField label={'Age:'} form={form} name="age" />
117 <SubmitButton form={form} />
118 <button type="reset" onClick={() => form.reset()}>
119 Reset
120 </button>
121 </form>
122 </div>
123 )
125​
126const rootElement = document.getElementById('root')!
127​
128createRoot(rootElement).render(
129 <React.StrictMode>
130 <App />
131 </React.StrictMode>,