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

quick-start.md

120 lines3.0 KB

1---
2id: quick-start
3title: Quick Start
4---
5​
6TanStack Form is a headless, type-safe form library. It owns form state and
7validation while leaving markup, styling, and component choice to you.
8​
9Install the Preact adapter:
10​
11```bash
12npm install @tanstack/preact-form
13```
14​
15## Create a form
16​
17`useForm` requires `defaultValues`. Their shape becomes the form's inferred
18value type.
19​
20```tsx
21import { useForm } from '@tanstack/preact-form'
22​
23export function ProfileForm() {
24 const form = useForm({
25 defaultValues: {
26 fullName: '',
27 age: 0,
28 },
29 onSubmit: async ({ value }) => {
30 console.log(value)
31 },
32 })
33​
34 return (
35 <form
36 onSubmit={(event) => {
37 event.preventDefault()
38 void form.handleSubmit()
39 }}
40 >
41 <form.Field
42 name="fullName"
43 validators={[
44 {
45 triggers: ['change', 'blur'],
46 run: ({ value }) =>
47 value.trim() ? undefined : 'Enter your full name',
48 },
49 ]}
50 >
51 {(field) => (
52 <label>
53 Full name
54 <input
55 name={field.name}
56 value={field.value}
57 onBlur={field.handleBlur}
58 onInput={(event) => field.handleChange(event.currentTarget.value)}
59 aria-invalid={field.meta.isInvalid}
60 />
61 {field.errors.map((error) => (
62 <span key={error.message} role="alert">
63 {error.message}
64 </span>
65 ))}
66 </label>
67 )}
68 </form.Field>
69​
70 <form.Field
71 name="age"
72 validators={[
73 {
74 triggers: ['change'],
75 run: ({ value }) =>
76 value >= 13 ? undefined : 'You must be at least 13',
77 },
78 ]}
79 >
80 {(field) => (
81 <label>
82 Age
83 <input
84 name={field.name}
85 type="number"
86 value={field.value}
87 onBlur={field.handleBlur}
88 onInput={(event) =>
89 field.handleChange(event.currentTarget.valueAsNumber)
90 }
91 aria-invalid={field.meta.isInvalid}
92 />
93 </label>
94 )}
95 </form.Field>
96​
97 <form.Subscribe
98 selector={(state) => [state.canSubmit, state.isSubmitting]}
99 >
100 {([canSubmit, isSubmitting]) => (
101 <button type="submit" disabled={!canSubmit || isSubmitting}>
102 {isSubmitting ? 'Saving…' : 'Save'}
103 </button>
104 )}
105 </form.Subscribe>
106 </form>
107 )
109```
110​
111The important pieces are:
112​
113- `defaultValues` define the complete initial value and drive type inference.
114- `form.Field` subscribes to one field. Its render prop exposes `field.value`,
115 `field.meta`, and event handlers.
116- Validators are ordered objects with a `run` function and explicit
117 `triggers`.
118- `form.Subscribe` rerenders only its own children when the selected form state
119 changes.
120- `form.handleSubmit()` validates the form before calling `onSubmit`.