@rsc-kit/mcp 0.41.0 → 0.42.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/recipes.js +18 -2
- package/dist/recipes.js.map +1 -1
- package/guides/admin-plugins.md +206 -6
- package/guides/api-routes.md +159 -215
- package/guides/authorization.md +103 -114
- package/guides/backend-answered-pages.md +301 -252
- package/guides/bap-vs-inertia.md +67 -25
- package/guides/blueprints.md +300 -169
- package/guides/bun.md +42 -25
- package/guides/caching.md +46 -49
- package/guides/coming-from-inertia.md +2 -2
- package/guides/commands.md +251 -200
- package/guides/connection.md +50 -54
- package/guides/content-security-policy.md +133 -84
- package/guides/domains.md +190 -149
- package/guides/edge-caching.md +242 -268
- package/guides/emails.md +96 -45
- package/guides/errors.md +116 -137
- package/guides/feature-flags.md +100 -30
- package/guides/file-uploads.md +101 -26
- package/guides/fonts.md +139 -110
- package/guides/forms.md +520 -542
- package/guides/images.md +87 -28
- package/guides/index.json +13 -33
- package/guides/instrumentation.md +134 -95
- package/guides/isr.md +3 -3
- package/guides/live-data-in-production.md +695 -0
- package/guides/live-data.md +170 -839
- package/guides/mcp.md +83 -59
- package/guides/metadata.md +124 -179
- package/guides/navigation.md +118 -147
- package/guides/no-javascript.md +49 -57
- package/guides/offline.md +118 -153
- package/guides/openapi.md +100 -35
- package/guides/pages.md +160 -50
- package/guides/ppr.md +178 -256
- package/guides/pwa.md +270 -216
- package/guides/queries.md +171 -300
- package/guides/react-compiler.md +90 -50
- package/guides/redirects.md +141 -177
- package/guides/response-headers.md +76 -74
- package/guides/route-interception.md +112 -111
- package/guides/routing.md +216 -322
- package/guides/sections.md +63 -66
- package/guides/seo-files.md +127 -65
- package/guides/server-actions.md +285 -357
- package/guides/static-generation.md +131 -199
- package/guides/testing.md +269 -147
- package/guides/third-party-scripts.md +94 -47
- package/guides/typed-routes.md +115 -113
- package/guides/url-validation.md +113 -61
- package/guides/validation.md +53 -62
- package/guides/view-transitions.md +159 -132
- package/guides/where-it-runs.md +226 -162
- package/package.json +2 -2
- package/guides/admin.md +0 -520
- package/guides/deployment.md +0 -598
- package/guides/go.md +0 -539
- package/guides/laravel.md +0 -787
- package/guides/your-own-backend.md +0 -602
package/guides/forms.md
CHANGED
|
@@ -2,29 +2,35 @@
|
|
|
2
2
|
|
|
3
3
|
> Progressive forms, pending state and validation errors.
|
|
4
4
|
|
|
5
|
-
`<Form>` submits to a server action:
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
GET-form navigation.
|
|
5
|
+
`<Form>` submits to a server action and handles the state around it: pending,
|
|
6
|
+
validation errors, success and optimistic updates. It works before the page's
|
|
7
|
+
JavaScript has loaded.
|
|
9
8
|
|
|
10
|
-
|
|
9
|
+
```tsx title="NewOrder.tsx"
|
|
10
|
+
"use client";
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
`FormData` on submit. No `useState` per field, no `value`/`onChange` pair,
|
|
15
|
-
no re-render of the whole form on every keystroke — and after a refused
|
|
16
|
-
submit the values are still there, because nothing re-rendered the inputs.
|
|
12
|
+
import { Form } from "@rsc-kit/core/form";
|
|
13
|
+
import * as orders from "../server-actions/orders";
|
|
17
14
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
15
|
+
export function NewOrder() {
|
|
16
|
+
return (
|
|
17
|
+
<Form action={orders.create}>
|
|
18
|
+
{({ pending, error }) => (
|
|
19
|
+
<>
|
|
20
|
+
<input name="title" />
|
|
21
|
+
{error('title') && <p>{error('title')}</p>}
|
|
22
|
+
<button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
|
|
23
|
+
</>
|
|
24
|
+
)}
|
|
25
|
+
</Form>
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
```
|
|
24
29
|
|
|
25
|
-
##
|
|
30
|
+
## Submitting a form
|
|
26
31
|
|
|
27
|
-
|
|
32
|
+
Pass a server action as `action`. The children are a function that receives the
|
|
33
|
+
form's state:
|
|
28
34
|
|
|
29
35
|
```tsx title="TodoForm.tsx"
|
|
30
36
|
"use client";
|
|
@@ -41,9 +47,7 @@ export default function TodoForm() {
|
|
|
41
47
|
<>
|
|
42
48
|
<input name="title" placeholder="What needs to be done?" />
|
|
43
49
|
{error('title') && <span className="text-red-500">{error('title')}</span>}
|
|
44
|
-
<button disabled={pending}>
|
|
45
|
-
{pending ? 'Adding...' : 'Add Todo'}
|
|
46
|
-
</button>
|
|
50
|
+
<button disabled={pending}>{pending ? 'Adding...' : 'Add Todo'}</button>
|
|
47
51
|
</>
|
|
48
52
|
)}
|
|
49
53
|
</Form>
|
|
@@ -51,50 +55,50 @@ export default function TodoForm() {
|
|
|
51
55
|
}
|
|
52
56
|
```
|
|
53
57
|
|
|
54
|
-
The
|
|
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
|
-
|
|
58
|
+
The inputs are ordinary named inputs. They keep their own value, and the action
|
|
59
|
+
reads them as `FormData` on submit. There's no `useState` per field and no
|
|
60
|
+
`value`/`onChange` pair, and typing doesn't re-render the form. Bind a field
|
|
61
|
+
only when the page has to react as it's typed: see
|
|
62
|
+
[controlling one field](#controlling-one-field).
|
|
63
|
+
|
|
64
|
+
The type parameter, `<FormValues>`, types the names `error()` accepts. With a
|
|
65
|
+
generated action you don't need it: the names come from the action.
|
|
66
|
+
|
|
67
|
+
What the render function receives:
|
|
68
|
+
|
|
69
|
+
| Name | What it is |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `error(name)` | The field's message, or `undefined`. |
|
|
72
|
+
| `formError` | A refusal that isn't about one field. |
|
|
73
|
+
| `field(name)` | A binding to spread onto a control you need to hold. |
|
|
74
|
+
| `pending` | `true` while the submit is running. |
|
|
75
|
+
| `dirty` | Whether any value differs from what the form started with. |
|
|
76
|
+
| `succeeded`, `recentlySucceeded` | Whether the last submit succeeded; the second for two seconds only. |
|
|
77
|
+
| `reset()`, `clearErrors()` | Go back to the starting values; clear the errors. |
|
|
78
|
+
| `validate()`, `validating`, `valid(name)` | Ask the server to check fields now. |
|
|
79
|
+
|
|
80
|
+
### Form props
|
|
81
|
+
|
|
82
|
+
| Prop | What it does |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `action` | A server action (POST), or a URL (GET). |
|
|
85
|
+
| `method` | `"get"` or `"post"`. Defaults to `"post"` for an action and `"get"` for a URL. |
|
|
86
|
+
| `schema` | A schema to check the values with in the browser. |
|
|
87
|
+
| `defaultValues` | Starting values for bound fields. |
|
|
88
|
+
| `fields` | Field names, for a form whose values aren't posted fields. |
|
|
89
|
+
| `resetOnSuccess` | Reset the form after a successful submit. Default `true`. |
|
|
90
|
+
| `optimistic` | Called inside the transition, for [optimistic updates](#optimistic-updates). |
|
|
91
|
+
| `onSuccess` | Called with the action's result. |
|
|
92
|
+
| `onError` | Called with the validation errors on a 422. |
|
|
93
|
+
| `onSubmit` | Called before submitting. Return `false` to cancel. |
|
|
94
|
+
| `prefetch` | `"hover"` (default), `"mount"` or `"none"`. GET forms only. |
|
|
95
|
+
| `replace` | Replace the history entry. GET forms only. |
|
|
96
|
+
| `preserveScroll` | Keep the scroll position. GET forms only. |
|
|
93
97
|
|
|
94
98
|
### In a component of its own
|
|
95
99
|
|
|
96
|
-
`useForm()` returns
|
|
97
|
-
|
|
100
|
+
`useForm()` returns what the render function receives, so part of a form can
|
|
101
|
+
move into its own component:
|
|
98
102
|
|
|
99
103
|
```tsx title="SubmitButton.tsx"
|
|
100
104
|
"use client";
|
|
@@ -112,109 +116,36 @@ export function SubmitButton() {
|
|
|
112
116
|
}
|
|
113
117
|
```
|
|
114
118
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
---
|
|
119
|
-
|
|
120
|
-
### Field names
|
|
121
|
-
|
|
122
|
-
`error()` and `clearErrors()` are typed from the action's input, so a typo
|
|
123
|
-
fails `tsc` rather than silently never matching:
|
|
124
|
-
|
|
125
|
-
```tsx
|
|
126
|
-
<Form action={orders.create}>
|
|
127
|
-
{({ error }) => (
|
|
128
|
-
<>
|
|
129
|
-
{error('name')} {/* ok */}
|
|
130
|
-
{error('address.city')} {/* ok: a nested path */}
|
|
131
|
-
{error('items.0.sku')} {/* ok: a list's index */}
|
|
132
|
-
{error('nmae')} {/* type error */}
|
|
133
|
-
</>
|
|
134
|
-
)}
|
|
135
|
-
</Form>
|
|
136
|
-
```
|
|
137
|
-
|
|
138
|
-
Where the names come from: a generated stub's typed parameter (the backend
|
|
139
|
-
already lists the fields of the struct or the FormRequest-shaped array it takes
|
|
140
|
-
in `rsc-host.json`, so nothing is written for this), or `createActionClient()`'s
|
|
141
|
-
`.input(schema)`. Fields the form declares in `defaultValues` count too. When
|
|
142
|
-
the action says nothing — a function of a `FormData`, a url, a cast — nothing is
|
|
143
|
-
claimed and any name is accepted, as before. A name the backend reports that its
|
|
144
|
-
input does not have, such as a key it computes, is a type error you can answer by
|
|
145
|
-
declaring it in `defaultValues`.
|
|
146
|
-
|
|
147
|
-
**A wrapper you write around a stub** says nothing on its own: a function of a
|
|
148
|
-
`FormData` could read anything. Declare the fields on its parameter, where the
|
|
149
|
-
code that reads them lives:
|
|
150
|
-
|
|
151
|
-
```tsx
|
|
152
|
-
import type { FormFields } from '@rsc-kit/core/form'
|
|
153
|
-
|
|
154
|
-
export async function renameApp(form: FormFields<'id' | 'name'>) {
|
|
155
|
-
'use server'
|
|
156
|
-
await appsRename(String(form.get('id')), String(form.get('name')))
|
|
157
|
-
}
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
`<Form action={renameApp}>` then closes `error()` to `id` and `name` — and to
|
|
161
|
-
whatever `defaultValues` adds. A `FormFields` is a `FormData`; nothing runs, and
|
|
162
|
-
the names are a claim the types keep, not a check the browser makes. It names
|
|
163
|
-
what `error()` may be asked for, so a field the backend refuses under that the
|
|
164
|
-
form does not post — `redirect`, say — belongs in the same list.
|
|
165
|
-
|
|
166
|
-
**A team-scoped action**, `func(ctx, team string, in NewApp)`, is a form's action
|
|
167
|
-
once the team is bound. A form fills the struct parameter, the one after
|
|
168
|
-
whatever you bound, and the generated stub keeps its field names:
|
|
169
|
-
|
|
170
|
-
```tsx
|
|
171
|
-
const create = apps.create.bind(null, team) // once, not inline
|
|
172
|
-
|
|
173
|
-
<Form action={create}>{({ error }) => error('name')}</Form>
|
|
174
|
-
```
|
|
175
|
-
|
|
176
|
-
Bind into a `const` first. Written inline in the JSX, TypeScript reads `bind`'s
|
|
177
|
-
result before the form's render function is known and the names are not
|
|
178
|
-
carried: the form still compiles, and is open as it always was. A stub whose
|
|
179
|
-
parameters are all plain strings has no struct for a form to fill — wrap it, as
|
|
180
|
-
above.
|
|
181
|
-
|
|
182
|
-
**A form that posts nothing** — its values live in React state, or it is a
|
|
183
|
-
button — has no `FormData` to name the fields on. Name them on the form:
|
|
184
|
-
|
|
185
|
-
```tsx
|
|
186
|
-
<Form action={resize} fields={['size', 'copies']}>
|
|
187
|
-
{({ error }) => error('size')} {/* error('sise') fails the typecheck */}
|
|
188
|
-
</Form>
|
|
189
|
-
```
|
|
119
|
+
This isn't React's `useFormStatus`, which is a different hook with a different
|
|
120
|
+
answer.
|
|
190
121
|
|
|
191
|
-
|
|
192
|
-
and `defaultValues`. It is types only: nothing is checked in the browser. It is
|
|
193
|
-
also how to name a field the backend refuses under that the struct does not
|
|
194
|
-
spell the same way, such as an untagged Go field `Host` that the backend reports
|
|
195
|
-
as `host`; tagging the struct (`json:"host"`) is the cleaner fix.
|
|
122
|
+
## Validation errors
|
|
196
123
|
|
|
197
|
-
|
|
124
|
+
When a submit fails validation, `error('title')` returns the field's message.
|
|
125
|
+
There's no `try`/`catch` to write and no state to hold.
|
|
198
126
|
|
|
199
127
|
```tsx
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
128
|
+
{error('title') && <p>{error('title')}</p>}
|
|
129
|
+
{error('address.city')} {/* a nested field */}
|
|
130
|
+
{error('items[0].name')} {/* a field in a list */}
|
|
131
|
+
{formError && <p role="alert">{formError}</p>}
|
|
203
132
|
```
|
|
204
133
|
|
|
205
|
-
|
|
134
|
+
- **`error(name)`** shows a field's message. `!!error('title')` tells you
|
|
135
|
+
whether the field is invalid.
|
|
136
|
+
- **`formError`** is a refusal that isn't about one field: the action's
|
|
137
|
+
`serverError`, such as a payment required or a slot just taken, or a message
|
|
138
|
+
for the whole form. It clears with the field errors.
|
|
139
|
+
- A failure on the way, such as the network, goes to `onError` instead.
|
|
206
140
|
|
|
207
|
-
|
|
208
|
-
|
|
141
|
+
Errors come from the schema in the browser and from the server, and `error()`
|
|
142
|
+
shows both. Where the server's come from depends on your backend: see
|
|
143
|
+
[Validation](/guides/validation).
|
|
209
144
|
|
|
210
|
-
|
|
211
|
-
care. See [Validation](/guides/validation).
|
|
145
|
+
### Returning an error from an action
|
|
212
146
|
|
|
213
|
-
An action can
|
|
214
|
-
|
|
215
|
-
`fieldErrors` arrives with the handler's arguments, typed to its input. A plain
|
|
216
|
-
`"use server"` function has no input type to draw on, so it imports the same
|
|
217
|
-
thing untyped:
|
|
147
|
+
An action can refuse a field itself, for something no schema could know.
|
|
148
|
+
Return `fieldErrors()`:
|
|
218
149
|
|
|
219
150
|
```ts
|
|
220
151
|
'use server';
|
|
@@ -230,221 +161,117 @@ export async function addTodo(formData: FormData) {
|
|
|
230
161
|
}
|
|
231
162
|
```
|
|
232
163
|
|
|
233
|
-
|
|
234
|
-
|
|
164
|
+
The form shows it under that field, the same as a schema failure. Through the
|
|
165
|
+
[action client](/guides/server-actions#failing-on-something-a-schema-cannot-know),
|
|
166
|
+
`fieldErrors` arrives with the handler's arguments, typed to its input.
|
|
235
167
|
|
|
236
|
-
|
|
168
|
+
## Field names
|
|
237
169
|
|
|
238
|
-
|
|
170
|
+
`error()` and `clearErrors()` are typed from the action's input, so a typo fails
|
|
171
|
+
the typecheck instead of never matching:
|
|
239
172
|
|
|
240
|
-
|
|
173
|
+
```tsx
|
|
174
|
+
<Form action={orders.create}>
|
|
175
|
+
{({ error }) => (
|
|
176
|
+
<>
|
|
177
|
+
{error('name')} {/* ok */}
|
|
178
|
+
{error('address.city')} {/* ok: a nested path */}
|
|
179
|
+
{error('items.0.sku')} {/* ok: a list's index */}
|
|
180
|
+
{error('nmae')} {/* type error */}
|
|
181
|
+
</>
|
|
182
|
+
)}
|
|
183
|
+
</Form>
|
|
184
|
+
```
|
|
241
185
|
|
|
242
|
-
|
|
243
|
-
"use client";
|
|
186
|
+
The names come from:
|
|
244
187
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
188
|
+
- a generated action's parameter. The backend lists the fields of the struct or
|
|
189
|
+
form request it takes in `rsc-host.json`, so you write nothing.
|
|
190
|
+
- `createActionClient()`'s `.input(schema)`.
|
|
191
|
+
- `defaultValues` on the form.
|
|
248
192
|
|
|
249
|
-
|
|
193
|
+
When the action says nothing about its input - a function of `FormData`, a URL,
|
|
194
|
+
a cast - any name is accepted. A name the backend reports that its input
|
|
195
|
+
doesn't have, such as a key it computes, is a type error: add it to
|
|
196
|
+
`defaultValues`.
|
|
250
197
|
|
|
251
|
-
|
|
252
|
-
const [optimisticTodos, addOptimistic] = useOptimistic(
|
|
253
|
-
todos,
|
|
254
|
-
(state, newTodo: Todo) => [...state, newTodo]
|
|
255
|
-
);
|
|
198
|
+
### Typing a wrapper around an action
|
|
256
199
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
<ul>
|
|
260
|
-
{optimisticTodos.map((todo) => (
|
|
261
|
-
<li key={todo.id}>{todo.title}</li>
|
|
262
|
-
))}
|
|
263
|
-
</ul>
|
|
200
|
+
A function of `FormData` could read anything, so it names no fields. Declare
|
|
201
|
+
them on its parameter with `FormFields`:
|
|
264
202
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
addOptimistic({ id: Date.now(), title: data.title as string, done: false })
|
|
269
|
-
}
|
|
270
|
-
>
|
|
271
|
-
<input name="title" />
|
|
272
|
-
<button>Add</button>
|
|
273
|
-
</Form>
|
|
274
|
-
</div>
|
|
275
|
-
);
|
|
276
|
-
}
|
|
277
|
-
```
|
|
278
|
-
|
|
279
|
-
## Search and filter forms
|
|
280
|
-
|
|
281
|
-
When `action` is a URL string, the form navigates via RSC instead of doing a full page reload. Form fields are serialized as query parameters. Supports prefetching for instant navigation.
|
|
282
|
-
|
|
283
|
-
```tsx title="SearchForm.tsx"
|
|
284
|
-
"use client";
|
|
285
|
-
|
|
286
|
-
import { Form } from "@rsc-kit/core/form";
|
|
203
|
+
```tsx
|
|
204
|
+
import type { FormFields } from '@rsc-kit/core/form'
|
|
205
|
+
import * as apps from './server-actions/apps'
|
|
287
206
|
|
|
288
|
-
export
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
<input name="q" placeholder="Search..." />
|
|
292
|
-
<select name="sort">
|
|
293
|
-
<option value="relevance">Relevance</option>
|
|
294
|
-
<option value="date">Date</option>
|
|
295
|
-
</select>
|
|
296
|
-
<button>Search</button>
|
|
297
|
-
</Form>
|
|
298
|
-
);
|
|
207
|
+
export async function renameApp(form: FormFields<'id' | 'name'>) {
|
|
208
|
+
'use server'
|
|
209
|
+
await apps.rename(String(form.get('id')), String(form.get('name')))
|
|
299
210
|
}
|
|
300
211
|
```
|
|
301
212
|
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
213
|
+
`<Form action={renameApp}>` then accepts `error('id')` and `error('name')`, plus
|
|
214
|
+
whatever `defaultValues` adds. A `FormFields` is a `FormData`: the names are
|
|
215
|
+
types only, and nothing is checked in the browser. Include a field the backend
|
|
216
|
+
may refuse that the form doesn't post, such as `redirect`.
|
|
305
217
|
|
|
306
|
-
|
|
218
|
+
### Binding an argument first
|
|
307
219
|
|
|
308
|
-
|
|
220
|
+
For an action like `func(ctx, team string, in NewApp)`, bind the team and the
|
|
221
|
+
form fills the struct after it. Bind into a `const` first:
|
|
309
222
|
|
|
310
|
-
```tsx
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
import { Form } from "@rsc-kit/core/form";
|
|
314
|
-
|
|
315
|
-
export default function Lookup() {
|
|
316
|
-
return (
|
|
317
|
-
<Form action="/lookup" method="get">
|
|
318
|
-
{({ pending }) => (
|
|
319
|
-
<>
|
|
320
|
-
<input name="q" />
|
|
321
|
-
<button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
|
|
322
|
-
</>
|
|
323
|
-
)}
|
|
324
|
-
</Form>
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
```
|
|
328
|
-
|
|
329
|
-
To show a skeleton where the results are instead of the old results, style them from the form's own `data-pending` attribute. The results stay outside the form, and nothing in the page is a client component for it:
|
|
223
|
+
```tsx
|
|
224
|
+
const create = apps.create.bind(null, team) // once, not inline
|
|
330
225
|
|
|
331
|
-
|
|
332
|
-
#results-skeleton { display: none }
|
|
333
|
-
section:has(form[data-pending]) #results { display: none }
|
|
334
|
-
section:has(form[data-pending]) #results-skeleton { display: block }
|
|
226
|
+
<Form action={create}>{({ error }) => error('name')}</Form>
|
|
335
227
|
```
|
|
336
228
|
|
|
337
|
-
|
|
229
|
+
Written inline in the JSX, TypeScript loses the names: the form compiles, but
|
|
230
|
+
accepts any name. An action whose parameters are all plain strings has no
|
|
231
|
+
struct for a form to fill, so wrap it as above.
|
|
338
232
|
|
|
339
|
-
|
|
233
|
+
### A form that posts nothing
|
|
340
234
|
|
|
341
|
-
|
|
342
|
-
|
|
235
|
+
When the values live in React state, or the form is a single button, name the
|
|
236
|
+
fields on the form:
|
|
343
237
|
|
|
344
238
|
```tsx
|
|
345
|
-
<Form action={
|
|
346
|
-
{({
|
|
347
|
-
<>
|
|
348
|
-
<Label htmlFor="title">Title</Label>
|
|
349
|
-
<Input id="title" name="title" />
|
|
350
|
-
{error('title') && <p className="text-destructive">{error('title')}</p>}
|
|
351
|
-
|
|
352
|
-
<Select name="kind">
|
|
353
|
-
<SelectTrigger><SelectValue /></SelectTrigger>
|
|
354
|
-
<SelectContent>
|
|
355
|
-
<SelectItem value="post">Post</SelectItem>
|
|
356
|
-
</SelectContent>
|
|
357
|
-
</Select>
|
|
358
|
-
|
|
359
|
-
<Checkbox name="draft" />
|
|
360
|
-
|
|
361
|
-
<Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
|
|
362
|
-
</>
|
|
363
|
-
)}
|
|
239
|
+
<Form action={resize} fields={['size', 'copies']}>
|
|
240
|
+
{({ error }) => error('size')} {/* error('sise') fails the typecheck */}
|
|
364
241
|
</Form>
|
|
365
242
|
```
|
|
366
243
|
|
|
367
|
-
`
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
shadcn is built on Base UI or on Radix. Both render a hidden native control
|
|
372
|
-
whenever you give the component a `name`, for exactly this. Omit the `name` and
|
|
373
|
-
it is invisible to the form; that is the only thing to remember.
|
|
374
|
-
|
|
375
|
-
A pick in a Base UI `Select` changes its hidden control without firing an
|
|
376
|
-
event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
|
|
377
|
-
the change.
|
|
244
|
+
`fields` adds to the action's own names and `defaultValues`. It is types only.
|
|
245
|
+
It also names a field the backend reports under a different spelling, such as
|
|
246
|
+
an untagged Go field `Host` reported as `host`, though tagging the struct
|
|
247
|
+
(`json:"host"`) is the cleaner fix.
|
|
378
248
|
|
|
379
|
-
|
|
380
|
-
shadcn's `<Form>`, `<FormField>` and `<FormControl>` are wrappers around
|
|
381
|
-
[react-hook-form](https://react-hook-form.com), which is a different system for
|
|
382
|
-
the same job — its own state, its own validation, its own submit. Use one or
|
|
383
|
-
the other, not both.
|
|
384
|
-
|
|
385
|
-
Ours gives you the field errors the *server* returned, which is the half a
|
|
386
|
-
client-side library cannot do.
|
|
387
|
-
:::
|
|
388
|
-
|
|
389
|
-
### shadcn's `Field` components
|
|
390
|
-
|
|
391
|
-
The newer `Field`, `FieldLabel`, `FieldError` and `FieldGroup` are plain
|
|
392
|
-
presentational components — they take props rather than reading a form
|
|
393
|
-
library's context, which is what the older `<FormField>` did. So they work here
|
|
394
|
-
directly:
|
|
249
|
+
A component below the form types its prop with `FieldNamesOf`:
|
|
395
250
|
|
|
396
251
|
```tsx
|
|
397
|
-
|
|
398
|
-
{({ pending, error }) => (
|
|
399
|
-
<FieldGroup>
|
|
400
|
-
<Field data-invalid={!!error('title')}>
|
|
401
|
-
<FieldLabel htmlFor="title">Bug title</FieldLabel>
|
|
402
|
-
<Input id="title" name="title" aria-invalid={!!error('title')} />
|
|
403
|
-
<FieldDescription>Keep it short and specific.</FieldDescription>
|
|
404
|
-
<FieldError>{error('title')}</FieldError>
|
|
405
|
-
</Field>
|
|
252
|
+
import type { FieldNamesOf } from '@rsc-kit/core/form'
|
|
406
253
|
|
|
407
|
-
|
|
408
|
-
{pending ? 'Sending…' : 'Submit'}
|
|
409
|
-
</Button>
|
|
410
|
-
</FieldGroup>
|
|
411
|
-
)}
|
|
412
|
-
</Form>
|
|
254
|
+
type Props = { name: FieldNamesOf<typeof orders.create> }
|
|
413
255
|
```
|
|
414
256
|
|
|
415
|
-
|
|
416
|
-
so `error('title')` goes straight in. Everything else is the same markup you
|
|
417
|
-
would write with any other form library.
|
|
418
|
-
|
|
419
|
-
The difference is where the errors came from. With TanStack Form or
|
|
420
|
-
react-hook-form those are the *client's* validation; here `error()` answers with
|
|
421
|
-
the client's **and** whatever the server sent back, because a refused action
|
|
422
|
-
returns its fields rather than throwing them away.
|
|
423
|
-
|
|
424
|
-
### Setting the values
|
|
257
|
+
## Setting the values
|
|
425
258
|
|
|
426
|
-
|
|
427
|
-
own, nothing of ours:
|
|
259
|
+
An initial value is React's own `defaultValue`:
|
|
428
260
|
|
|
429
261
|
```tsx
|
|
430
262
|
<Input id="title" name="title" defaultValue={post.title} />
|
|
431
263
|
```
|
|
432
264
|
|
|
433
|
-
After a refused submit the values are still there, because
|
|
434
|
-
|
|
435
|
-
not owning the value.
|
|
265
|
+
After a refused submit the values are still there, because nothing re-rendered
|
|
266
|
+
the inputs.
|
|
436
267
|
|
|
437
|
-
The exception is a submit
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
as `defaultValue`.
|
|
268
|
+
The exception is a submit made before the page's JavaScript loaded, which
|
|
269
|
+
reloads the page. The server renders the page again, so return the values from
|
|
270
|
+
the action and render them as `defaultValue`.
|
|
441
271
|
|
|
442
|
-
|
|
272
|
+
## How the values are read
|
|
443
273
|
|
|
444
|
-
|
|
445
|
-
is not there at all — a fact that used to leak into every schema as
|
|
446
|
-
`z.coerce.number()` and a per-checkbox `.transform()`. It does not any more.
|
|
447
|
-
The form is read *the way the schema means it*, on both sides:
|
|
274
|
+
Write the schema for the values you want, not for the strings a form posts:
|
|
448
275
|
|
|
449
276
|
```ts
|
|
450
277
|
const settings = z.object({
|
|
@@ -463,29 +290,31 @@ const settings = z.object({
|
|
|
463
290
|
})
|
|
464
291
|
```
|
|
465
292
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
`boolean` is `false
|
|
470
|
-
`number` is the number
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
293
|
+
No `z.coerce.number()` and no `.transform()` per checkbox. The form is read the
|
|
294
|
+
way the schema describes it, in the browser and again in the action:
|
|
295
|
+
|
|
296
|
+
- A `boolean` that is absent is `false`. `"on"` or `"1"` is `true`.
|
|
297
|
+
- A numeric string for a `number` is the number. An empty one for an optional
|
|
298
|
+
number is absent.
|
|
299
|
+
- An `array` given one value is a list of one, and given nothing is empty.
|
|
300
|
+
- Nested names nest: `fields[0][name]` and `fields[0].name` alike.
|
|
301
|
+
- A union takes the branch its discriminator names.
|
|
302
|
+
- A blank control is absent for a field the schema doesn't require, so
|
|
303
|
+
`z.email().optional()` accepts an empty input. It is `""` for a field the
|
|
304
|
+
schema requires, so `z.string().min(1)` can refuse it.
|
|
305
|
+
- A value the schema refuses is refused as it was posted: `"many"` for a number
|
|
306
|
+
is the error you expect.
|
|
307
|
+
|
|
308
|
+
This needs a schema that describes itself (Standard JSON Schema). Zod 4 and
|
|
309
|
+
ArkType do. Valibot doesn't yet, and its values arrive as strings. A part the
|
|
310
|
+
JSON Schema can't describe, such as `z.date()` or a custom check, arrives as
|
|
311
|
+
posted, and the rest of the form is still read normally. A schema that can't
|
|
312
|
+
describe itself at all is reported once in development, with the library's
|
|
313
|
+
reason.
|
|
314
|
+
|
|
315
|
+
A value sent through `<Form transform>` is encoded the same way back, a boolean
|
|
316
|
+
as `"1"`/`"0"` and a nested object as `key[prop]`, and decodes to what was
|
|
317
|
+
given.
|
|
489
318
|
|
|
490
319
|
### Lists of values
|
|
491
320
|
|
|
@@ -497,17 +326,16 @@ A repeated name is an array:
|
|
|
497
326
|
// → { tags: ['react', 'vite'] }
|
|
498
327
|
```
|
|
499
328
|
|
|
500
|
-
With one ticked that is `'react'`,
|
|
501
|
-
|
|
502
|
-
an array:
|
|
329
|
+
With only one ticked, that is the string `'react'`, which `z.array()` refuses.
|
|
330
|
+
End the name in `[]` and it is always an array:
|
|
503
331
|
|
|
504
332
|
```tsx
|
|
505
333
|
<Checkbox name="tags[]" value="react" />
|
|
506
334
|
// → { tags: ['react'] }
|
|
507
335
|
```
|
|
508
336
|
|
|
509
|
-
The brackets are dropped from the key, and
|
|
510
|
-
|
|
337
|
+
The brackets are dropped from the key, and a value is written back the same
|
|
338
|
+
way, so a list survives a round trip.
|
|
511
339
|
|
|
512
340
|
### Nested and repeating groups
|
|
513
341
|
|
|
@@ -519,11 +347,10 @@ Names that describe a shape build it:
|
|
|
519
347
|
<input name="items[0][name]" /> // the same field, other spelling
|
|
520
348
|
```
|
|
521
349
|
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
dots too. A refused `address.city` is `error('address.city')`.
|
|
350
|
+
Errors come back under the same paths: a refused `address.city` is
|
|
351
|
+
`error('address.city')`.
|
|
525
352
|
|
|
526
|
-
Rows you add and remove are ordinary state
|
|
353
|
+
Rows you add and remove are ordinary state. Only the names have to line up:
|
|
527
354
|
|
|
528
355
|
```tsx
|
|
529
356
|
{rows.map((row, i) => (
|
|
@@ -531,85 +358,43 @@ Rows you add and remove are ordinary state; only the *names* have to line up:
|
|
|
531
358
|
))}
|
|
532
359
|
```
|
|
533
360
|
|
|
534
|
-
|
|
361
|
+
## When fields are checked
|
|
535
362
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
363
|
+
**A field is checked when it is left, not as it is typed**, and when the form is
|
|
364
|
+
submitted. So `error()` has nothing for a field nobody has reached yet, and
|
|
365
|
+
there's no separate "touched" state to check.
|
|
539
366
|
|
|
540
|
-
|
|
541
|
-
|
|
367
|
+
The form listens for `focusout` itself, so a plain `<Input name="title" />` is
|
|
368
|
+
covered without binding it.
|
|
542
369
|
|
|
543
|
-
|
|
544
|
-
<Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
|
|
545
|
-
{({ field, error }) => (
|
|
546
|
-
<Field data-invalid={!!error('description')}>
|
|
547
|
-
<FieldLabel htmlFor="description">Description</FieldLabel>
|
|
548
|
-
|
|
549
|
-
<InputGroup>
|
|
550
|
-
<InputGroupTextarea id="description" {...field('description')} rows={6} />
|
|
551
|
-
<InputGroupAddon align="block-end">
|
|
552
|
-
<InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
|
|
553
|
-
</InputGroupAddon>
|
|
554
|
-
</InputGroup>
|
|
555
|
-
|
|
556
|
-
<FieldError>{error('description')}</FieldError>
|
|
557
|
-
</Field>
|
|
558
|
-
)}
|
|
559
|
-
</Form>
|
|
560
|
-
```
|
|
561
|
-
|
|
562
|
-
It gives you `{ name, value, onChange, onBlur }` — the same four things
|
|
563
|
-
`<Controller>` does, for the same reason.
|
|
564
|
-
|
|
565
|
-
`onChange` takes either a DOM event or a bare value, so a native input and a
|
|
566
|
-
`Select` from Base UI or Radix both work without a wrapper. A bound field is still an ordinary
|
|
567
|
-
named input, so it arrives in `FormData` with everything else: there is one
|
|
568
|
-
source of truth, and nothing merges.
|
|
370
|
+
### Checking with the server before submit
|
|
569
371
|
|
|
570
|
-
|
|
571
|
-
|
|
372
|
+
When a field is left **having changed**, the form asks the server to check it.
|
|
373
|
+
The action's guards and validation run for that field, and the action itself
|
|
374
|
+
doesn't. The answer shows on `error()` like any other. This catches what a
|
|
375
|
+
schema in the browser can't know, such as an email that is already subscribed
|
|
376
|
+
or a coupon that has expired.
|
|
572
377
|
|
|
573
|
-
|
|
378
|
+
There's nothing to turn on. The actions that can be asked:
|
|
574
379
|
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
rather than each field listening for `blur`, so `<Input name="title" />` is
|
|
583
|
-
covered without being bound to anything.
|
|
584
|
-
|
|
585
|
-
### Checked by the server before it is submitted
|
|
586
|
-
|
|
587
|
-
A schema in the browser cannot know that an email is already subscribed, or
|
|
588
|
-
that a coupon has expired. The server can, and `<Form>` asks it: when a field
|
|
589
|
-
is left **having changed**, the form sends what it holds to the action marked
|
|
590
|
-
as a check. The action's guards and validation run for that field; the action
|
|
591
|
-
itself does not. Its answer lands on `error()` like any other.
|
|
592
|
-
|
|
593
|
-
Nothing to opt into. Which actions can be asked:
|
|
594
|
-
|
|
595
|
-
- a `createActionClient()` action with an input schema - its middleware and
|
|
596
|
-
schema run, its handler is skipped;
|
|
597
|
-
- a backend function the backend says it can check without running - in
|
|
598
|
-
Laravel, any action whose first parameter is a form request (its
|
|
599
|
-
`authorize()` and `rules()`, filtered to the field, as Laravel's
|
|
600
|
-
Precognition does);
|
|
601
|
-
- nothing else. A plain `"use server"` function cannot be stopped before its
|
|
380
|
+
- a `createActionClient()` action with an input schema. Its middleware and
|
|
381
|
+
schema run, and its handler is skipped.
|
|
382
|
+
- a backend function the backend can check without running it. In Laravel,
|
|
383
|
+
that is any action whose first parameter is a form request: its
|
|
384
|
+
`authorize()` and `rules()` run, filtered to the field, as Laravel's
|
|
385
|
+
Precognition does.
|
|
386
|
+
- nothing else. A plain `"use server"` function can't be stopped before its
|
|
602
387
|
body, so it is never called to check, and the form stops asking after the
|
|
603
388
|
first answer says so.
|
|
604
389
|
|
|
605
|
-
A field the browser's schema already refuses
|
|
606
|
-
|
|
607
|
-
|
|
390
|
+
A field the browser's schema already refuses isn't sent. A field left without
|
|
391
|
+
being changed isn't asked about again. A file is sent only when its own field
|
|
392
|
+
is the one being checked.
|
|
608
393
|
|
|
609
394
|
#### When a blur is not the moment
|
|
610
395
|
|
|
611
|
-
`validate()` asks now, about the fields you name
|
|
612
|
-
|
|
396
|
+
`validate()` asks now, about the fields you name, or every field with none. It
|
|
397
|
+
resolves `true` when they pass. Use it for a wizard's steps:
|
|
613
398
|
|
|
614
399
|
```tsx
|
|
615
400
|
<Form action={register}>
|
|
@@ -635,19 +420,18 @@ It resolves `true` when they pass. That is a wizard's step:
|
|
|
635
420
|
</Form>
|
|
636
421
|
```
|
|
637
422
|
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
`*` stands for one segment of a nested name, as in Laravel: `validate('items.*.sku')`.
|
|
642
|
-
For a field checked as it is typed, call `validate('handle')` from its
|
|
643
|
-
`onChange` - and debounce it yourself; the form does not decide how often you
|
|
644
|
-
may ask.
|
|
423
|
+
Keep each step's fields in the form while hidden (render them with `hidden`, not
|
|
424
|
+
conditionally), so the last step's submit sends every one.
|
|
645
425
|
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
426
|
+
- `*` stands for one segment of a nested name, as in Laravel:
|
|
427
|
+
`validate('items.*.sku')`.
|
|
428
|
+
- To check a field as it is typed, call `validate('handle')` from its
|
|
429
|
+
`onChange`, and debounce it yourself.
|
|
430
|
+
- `validating` is `true` while a check is out.
|
|
431
|
+
- `valid(name)` is `true` once a check of that field passed and it hasn't been
|
|
432
|
+
edited since. Use it for a tick beside the field, not for deciding anything.
|
|
649
433
|
|
|
650
|
-
|
|
434
|
+
## After a successful submit
|
|
651
435
|
|
|
652
436
|
```tsx
|
|
653
437
|
{({ succeeded, recentlySucceeded }) => (
|
|
@@ -655,12 +439,10 @@ not for deciding anything.
|
|
|
655
439
|
)}
|
|
656
440
|
```
|
|
657
441
|
|
|
658
|
-
`recentlySucceeded` is
|
|
659
|
-
and fades.
|
|
660
|
-
because the timer has to be cleared when the component goes away and that is
|
|
661
|
-
the part people forget.
|
|
442
|
+
`recentlySucceeded` is `succeeded` for two seconds only, for a tick that
|
|
443
|
+
appears and fades. The form clears the timer when the component goes away.
|
|
662
444
|
|
|
663
|
-
|
|
445
|
+
## Disabling save until something changes
|
|
664
446
|
|
|
665
447
|
```tsx
|
|
666
448
|
{({ dirty, reset }) => (
|
|
@@ -671,42 +453,49 @@ the part people forget.
|
|
|
671
453
|
)}
|
|
672
454
|
```
|
|
673
455
|
|
|
674
|
-
`dirty` is whether
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
the form's to answer and not something a component beside it could work
|
|
678
|
-
out. A successful submit makes the current values the new baseline;
|
|
679
|
-
`reset()` goes back to the first one. A bound control with no native
|
|
680
|
-
element behind it counts too, through the store. Only a form that reads
|
|
681
|
-
`dirty` is measured, and it renders once when the value first differs — not
|
|
682
|
-
on the keystrokes after — so a field that subscribes for itself keeps its
|
|
683
|
-
promise of rendering alone.
|
|
456
|
+
`dirty` is whether any value differs from what the form started with,
|
|
457
|
+
uncontrolled fields included. A successful submit makes the current values the
|
|
458
|
+
new starting point, and `reset()` goes back to the first one.
|
|
684
459
|
|
|
685
|
-
|
|
460
|
+
A form only measures `dirty` when something reads it, and it renders once when
|
|
461
|
+
the value first differs, not on every keystroke after.
|
|
686
462
|
|
|
687
|
-
|
|
688
|
-
`<form.Field name="title" children={…}>`, `<Controller render={…}>`. It looks
|
|
689
|
-
like the more capable design, and the reason they need it is worth being precise
|
|
690
|
-
about, because the three of us are not in the same position.
|
|
463
|
+
## Controlling one field
|
|
691
464
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
render prop is what scopes that, and the verbosity is the price of it.
|
|
465
|
+
Bind a field with `field(name)` when it has no native element behind it, or
|
|
466
|
+
when you want to show its value as it's typed:
|
|
695
467
|
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
468
|
+
```tsx
|
|
469
|
+
<Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
|
|
470
|
+
{({ field, error }) => (
|
|
471
|
+
<Field data-invalid={!!error('description')}>
|
|
472
|
+
<FieldLabel htmlFor="description">Description</FieldLabel>
|
|
700
473
|
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
474
|
+
<InputGroup>
|
|
475
|
+
<InputGroupTextarea id="description" {...field('description')} rows={6} />
|
|
476
|
+
<InputGroupAddon align="block-end">
|
|
477
|
+
<InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
|
|
478
|
+
</InputGroupAddon>
|
|
479
|
+
</InputGroup>
|
|
705
480
|
|
|
706
|
-
|
|
707
|
-
|
|
481
|
+
<FieldError>{error('description')}</FieldError>
|
|
482
|
+
</Field>
|
|
483
|
+
)}
|
|
484
|
+
</Form>
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
`field()` returns `{ name, value, onChange, onBlur }`, like react-hook-form's
|
|
488
|
+
`<Controller>`. `onChange` takes a DOM event or a bare value, so a native input
|
|
489
|
+
and a Base UI or Radix `Select` both work without a wrapper. A bound field is
|
|
490
|
+
still a named input, so it is submitted with everything else.
|
|
491
|
+
|
|
492
|
+
Bind only the fields that need it and leave the rest alone.
|
|
493
|
+
|
|
494
|
+
### In its own component
|
|
708
495
|
|
|
709
|
-
|
|
496
|
+
`field()` re-renders the component holding the form. When a form is large, put
|
|
497
|
+
the field in its own component with `useField`, which re-renders that component
|
|
498
|
+
and nothing else:
|
|
710
499
|
|
|
711
500
|
```tsx
|
|
712
501
|
import { useField } from '@rsc-kit/core/form'
|
|
@@ -718,19 +507,9 @@ function Title() {
|
|
|
718
507
|
}
|
|
719
508
|
```
|
|
720
509
|
|
|
721
|
-
|
|
510
|
+
### Reading a value from elsewhere
|
|
722
511
|
|
|
723
|
-
|
|
724
|
-
its siblings. Which is what `<Controller>` achieves with a render prop, except
|
|
725
|
-
that the component you were going to write anyway is the boundary.
|
|
726
|
-
|
|
727
|
-
So the scoping is there when a form is large enough to need it, and the flat
|
|
728
|
-
markup is there when it is not.
|
|
729
|
-
|
|
730
|
-
### Reading the values from elsewhere
|
|
731
|
-
|
|
732
|
-
A preview, a summary, a count — something that shows a value without being the
|
|
733
|
-
field — reads it the same way the field does:
|
|
512
|
+
A preview, a summary or a count reads a value the same way:
|
|
734
513
|
|
|
735
514
|
```tsx
|
|
736
515
|
function Preview() {
|
|
@@ -740,27 +519,12 @@ function Preview() {
|
|
|
740
519
|
}
|
|
741
520
|
```
|
|
742
521
|
|
|
743
|
-
Only a
|
|
744
|
-
|
|
745
|
-
bind the field with `field()` or `useField` and it can be read.
|
|
522
|
+
Only a bound field can be read this way. An uncontrolled input's value is in
|
|
523
|
+
the DOM, so bind it with `field()` or `useField` first.
|
|
746
524
|
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
and a submit button outside it is `form="the-id"`.
|
|
751
|
-
|
|
752
|
-
Worth knowing what the alternatives do here, because it is not as different as
|
|
753
|
-
it looks. Reaching a form from another component is a context in all three:
|
|
754
|
-
react-hook-form has `<FormProvider>` and `useFormContext()`, and TanStack Form
|
|
755
|
-
has `createFormHookContexts()` with `useFormContext()` — which its own
|
|
756
|
-
documentation calls a bridge for integration constraints, to be avoided when
|
|
757
|
-
passing the form as a prop is possible. Ours needs no extra provider only
|
|
758
|
-
because `<Form>` already is one.
|
|
759
|
-
|
|
760
|
-
Where they are genuinely more flexible is *where the state is created*: their
|
|
761
|
-
`useForm()` is called by you, so it can be hoisted as far up as you like. For
|
|
762
|
-
the case where that matters — something that is not a descendant — create the
|
|
763
|
-
store yourself and hand it to the form:
|
|
525
|
+
`useForm()` and `useField()` work anywhere below `<Form>`. A submit button
|
|
526
|
+
outside the `<form>` element can use `form="the-id"`. For a component that isn't
|
|
527
|
+
below the form at all, create the store yourself and pass it to both:
|
|
764
528
|
|
|
765
529
|
```tsx
|
|
766
530
|
function Page() {
|
|
@@ -781,44 +545,258 @@ function TopBar({ store }) {
|
|
|
781
545
|
}
|
|
782
546
|
```
|
|
783
547
|
|
|
784
|
-
`useFormStore`
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
548
|
+
`useFormStore` holds the values only: no submit, no errors. Creating it doesn't
|
|
549
|
+
subscribe to it, so the component holding it doesn't re-render on every
|
|
550
|
+
keystroke.
|
|
551
|
+
|
|
552
|
+
## Optimistic updates
|
|
553
|
+
|
|
554
|
+
Pass `optimistic` and update React's `useOptimistic` state in it. It runs
|
|
555
|
+
inside the transition, so React reverts it if the action fails:
|
|
556
|
+
|
|
557
|
+
```tsx title="TodoList.tsx"
|
|
558
|
+
"use client";
|
|
559
|
+
|
|
560
|
+
import { useOptimistic } from "react";
|
|
561
|
+
import { Form } from "@rsc-kit/core/form";
|
|
562
|
+
import { addTodo } from "./actions";
|
|
563
|
+
|
|
564
|
+
type Todo = { id: number; title: string; done: boolean };
|
|
565
|
+
|
|
566
|
+
export default function TodoList({ todos }: { todos: Todo[] }) {
|
|
567
|
+
const [optimisticTodos, addOptimistic] = useOptimistic(
|
|
568
|
+
todos,
|
|
569
|
+
(state, newTodo: Todo) => [...state, newTodo]
|
|
570
|
+
);
|
|
571
|
+
|
|
572
|
+
return (
|
|
573
|
+
<div>
|
|
574
|
+
<ul>
|
|
575
|
+
{optimisticTodos.map((todo) => (
|
|
576
|
+
<li key={todo.id}>{todo.title}</li>
|
|
577
|
+
))}
|
|
578
|
+
</ul>
|
|
579
|
+
|
|
580
|
+
<Form
|
|
581
|
+
action={addTodo}
|
|
582
|
+
optimistic={(data) =>
|
|
583
|
+
addOptimistic({ id: Date.now(), title: data.title as string, done: false })
|
|
584
|
+
}
|
|
585
|
+
>
|
|
586
|
+
<input name="title" />
|
|
587
|
+
<button>Add</button>
|
|
588
|
+
</Form>
|
|
589
|
+
</div>
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
```
|
|
593
|
+
|
|
594
|
+
## Stopping bots
|
|
595
|
+
|
|
596
|
+
Put `<Honeypot />` inside the form:
|
|
597
|
+
|
|
598
|
+
```tsx
|
|
599
|
+
import { Form } from '@rsc-kit/core/form'
|
|
600
|
+
import { Honeypot } from '@rsc-kit/core/honeypot'
|
|
601
|
+
|
|
602
|
+
<Form action={subscribe}>
|
|
603
|
+
<input name="email" type="email" />
|
|
604
|
+
<Honeypot />
|
|
605
|
+
<button>Subscribe</button>
|
|
606
|
+
</Form>
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
It renders a field people never see. It is off screen, out of the tab order,
|
|
610
|
+
hidden from screen readers and not autofilled. A bot that fills in every input
|
|
611
|
+
fills that one too. Its post is answered as though it worked and dropped before
|
|
612
|
+
the action runs, so the action never sees it and the bot learns nothing.
|
|
613
|
+
|
|
614
|
+
- It works in any form that posts to a server action: `<Form>`, a plain
|
|
615
|
+
`<form action={…}>`, with JavaScript or without, and for a `"use server"`
|
|
616
|
+
function or a Laravel or Go action. The check happens in the renderer,
|
|
617
|
+
before the call reaches the backend.
|
|
618
|
+
- The trap is taken out of the form either way, so the action sees only the
|
|
619
|
+
fields a person filled in.
|
|
620
|
+
- The field is named `homepage`. `<Honeypot name="website" />` picks another
|
|
621
|
+
name, if the form has a real field called `homepage`. Forms without
|
|
622
|
+
`<Honeypot />` are not checked, so a `homepage` field elsewhere is ordinary.
|
|
623
|
+
|
|
624
|
+
It stops the crudest spam, not a determined attacker. A form worth attacking
|
|
625
|
+
wants a rate limit on its action as well, such as Laravel's `throttle`
|
|
626
|
+
middleware on the action class. [Blueprints](/guides/blueprints/#stopping-bots)
|
|
627
|
+
show it, and [protecting a server action](/guides/authorization/#protect-a-server-action)
|
|
628
|
+
covers guarding one written in JavaScript.
|
|
629
|
+
|
|
630
|
+
## Search and filter forms
|
|
631
|
+
|
|
632
|
+
When `action` is a URL, the form navigates to it with the fields as the query
|
|
633
|
+
string, without a full page reload:
|
|
788
634
|
|
|
789
|
-
|
|
790
|
-
|
|
635
|
+
```tsx title="SearchForm.tsx"
|
|
636
|
+
"use client";
|
|
637
|
+
|
|
638
|
+
import { Form } from "@rsc-kit/core/form";
|
|
639
|
+
|
|
640
|
+
export default function SearchForm() {
|
|
641
|
+
return (
|
|
642
|
+
<Form action="/search" method="get" prefetch="hover">
|
|
643
|
+
<input name="q" placeholder="Search..." />
|
|
644
|
+
<select name="sort">
|
|
645
|
+
<option value="relevance">Relevance</option>
|
|
646
|
+
<option value="date">Date</option>
|
|
647
|
+
</select>
|
|
648
|
+
<button>Search</button>
|
|
649
|
+
</Form>
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
This goes to `/search?q=hello&sort=date`, and the nearest Suspense boundary
|
|
655
|
+
streams in the results. With `prefetch="hover"`, hovering the submit button
|
|
656
|
+
starts loading the page.
|
|
657
|
+
|
|
658
|
+
### A search on the page it is on
|
|
659
|
+
|
|
660
|
+
When the form's `action` is the page the visitor is on, the page stays on
|
|
661
|
+
screen while the query runs, and the new results replace the old ones when
|
|
662
|
+
they arrive. The input keeps what was typed, a Suspense boundary already
|
|
663
|
+
showing content keeps showing it, and Back returns to the previous query.
|
|
664
|
+
|
|
665
|
+
`pending` stays `true` until the new results are on screen:
|
|
666
|
+
|
|
667
|
+
```tsx title="Lookup.tsx"
|
|
668
|
+
"use client";
|
|
669
|
+
|
|
670
|
+
import { Form } from "@rsc-kit/core/form";
|
|
671
|
+
|
|
672
|
+
export default function Lookup() {
|
|
673
|
+
return (
|
|
674
|
+
<Form action="/lookup" method="get">
|
|
675
|
+
{({ pending }) => (
|
|
676
|
+
<>
|
|
677
|
+
<input name="q" />
|
|
678
|
+
<button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
|
|
679
|
+
</>
|
|
680
|
+
)}
|
|
681
|
+
</Form>
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
```
|
|
685
|
+
|
|
686
|
+
To show a skeleton instead of the old results, style them from the form's
|
|
687
|
+
`data-pending` attribute. The results can stay outside the form, with no client
|
|
688
|
+
component for them:
|
|
689
|
+
|
|
690
|
+
```css
|
|
691
|
+
#results-skeleton { display: none }
|
|
692
|
+
section:has(form[data-pending]) #results { display: none }
|
|
693
|
+
section:has(form[data-pending]) #results-skeleton { display: block }
|
|
694
|
+
```
|
|
695
|
+
|
|
696
|
+
Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another
|
|
697
|
+
query loads it as a new page. The form doesn't prefetch the page it is already
|
|
698
|
+
on.
|
|
699
|
+
|
|
700
|
+
## Using it with shadcn/ui
|
|
701
|
+
|
|
702
|
+
shadcn's inputs work as they are, because `<Form>` reads the form's native
|
|
703
|
+
`FormData`:
|
|
704
|
+
|
|
705
|
+
```tsx
|
|
706
|
+
<Form action={createPost} schema={schema}>
|
|
707
|
+
{({ pending, error }) => (
|
|
708
|
+
<>
|
|
709
|
+
<Label htmlFor="title">Title</Label>
|
|
710
|
+
<Input id="title" name="title" />
|
|
711
|
+
{error('title') && <p className="text-destructive">{error('title')}</p>}
|
|
712
|
+
|
|
713
|
+
<Select name="kind">
|
|
714
|
+
<SelectTrigger><SelectValue /></SelectTrigger>
|
|
715
|
+
<SelectContent>
|
|
716
|
+
<SelectItem value="post">Post</SelectItem>
|
|
717
|
+
</SelectContent>
|
|
718
|
+
</Select>
|
|
719
|
+
|
|
720
|
+
<Checkbox name="draft" />
|
|
721
|
+
|
|
722
|
+
<Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
|
|
723
|
+
</>
|
|
724
|
+
)}
|
|
725
|
+
</Form>
|
|
726
|
+
```
|
|
727
|
+
|
|
728
|
+
- `Input`, `Textarea`, `Button` and `Label` are styled native elements.
|
|
729
|
+
- **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work**, on Base UI or
|
|
730
|
+
Radix. Each renders a hidden native control when you give it a `name`. Without
|
|
731
|
+
a `name`, the form can't see it.
|
|
732
|
+
- A pick in a Base UI `Select` changes its hidden control without firing an
|
|
733
|
+
event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
|
|
734
|
+
the change.
|
|
735
|
+
|
|
736
|
+
:::caution[Not shadcn's own `<Form>`]
|
|
737
|
+
shadcn's `<Form>`, `<FormField>` and `<FormControl>` wrap
|
|
738
|
+
[react-hook-form](https://react-hook-form.com), which has its own state,
|
|
739
|
+
validation and submit. Use one or the other, not both.
|
|
791
740
|
:::
|
|
792
741
|
|
|
742
|
+
### shadcn's `Field` components
|
|
743
|
+
|
|
744
|
+
`Field`, `FieldLabel`, `FieldError` and `FieldGroup` take props rather than
|
|
745
|
+
reading a form library's context, so they work directly:
|
|
746
|
+
|
|
747
|
+
```tsx
|
|
748
|
+
<Form action={reportBug} schema={formSchema}>
|
|
749
|
+
{({ pending, error }) => (
|
|
750
|
+
<FieldGroup>
|
|
751
|
+
<Field data-invalid={!!error('title')}>
|
|
752
|
+
<FieldLabel htmlFor="title">Bug title</FieldLabel>
|
|
753
|
+
<Input id="title" name="title" aria-invalid={!!error('title')} />
|
|
754
|
+
<FieldDescription>Keep it short and specific.</FieldDescription>
|
|
755
|
+
<FieldError>{error('title')}</FieldError>
|
|
756
|
+
</Field>
|
|
757
|
+
|
|
758
|
+
<Button type="submit" disabled={pending}>
|
|
759
|
+
{pending ? 'Sending…' : 'Submit'}
|
|
760
|
+
</Button>
|
|
761
|
+
</FieldGroup>
|
|
762
|
+
)}
|
|
763
|
+
</Form>
|
|
764
|
+
```
|
|
765
|
+
|
|
766
|
+
`FieldError` renders nothing when it has no children, so `error('title')` goes
|
|
767
|
+
straight in. Unlike with a client-side form library, `error()` includes the
|
|
768
|
+
errors the server sent back.
|
|
769
|
+
|
|
793
770
|
## It works before hydration
|
|
794
771
|
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
772
|
+
A form can be submitted before the page's JavaScript has loaded. The browser
|
|
773
|
+
posts it, and the page reloads with the result instead of updating in place.
|
|
774
|
+
There is nothing to turn on.
|
|
775
|
+
|
|
776
|
+
- The action runs as it would have otherwise, and a refusal shows on its
|
|
777
|
+
fields, `error('email')` included, for a visitor with no JavaScript at all.
|
|
778
|
+
- A `redirect()` from the action is followed, and a cookie it sets is kept.
|
|
779
|
+
- It is same origin only, as an action is, and the answer is never stored.
|
|
780
|
+
|
|
781
|
+
A stored page is the one most likely to be submitted this way, since it shows
|
|
782
|
+
before its JavaScript arrives. It is also why fields are real `name` attributes
|
|
783
|
+
rather than state: the browser can read them without help.
|
|
784
|
+
|
|
785
|
+
`<Form>` uses React's `useActionState` for this, and your action still takes
|
|
786
|
+
the `FormData` alone. A `useActionState` of your own works too, with an action
|
|
787
|
+
written for `(previousState, formData)`. Once the page has hydrated, the form
|
|
788
|
+
cancels the native submit and handles it itself.
|
|
789
|
+
|
|
790
|
+
## Coming from react-hook-form or TanStack Form
|
|
791
|
+
|
|
792
|
+
The default is react-hook-form's: fields are uncontrolled, and typing
|
|
793
|
+
re-renders nothing. TanStack Form is controlled-first, so it is the opposite.
|
|
794
|
+
|
|
795
|
+
| | react-hook-form | Here |
|
|
796
|
+
| --- | --- | --- |
|
|
797
|
+
| A plain field | `register('title')` | `name="title"` |
|
|
798
|
+
| A controlled field | `<Controller render={…}>` | `field('title')` |
|
|
799
|
+
| A field that re-renders alone | `<Controller>` | `useField('title')` in its own component |
|
|
800
|
+
| Reaching the form from below | `useFormContext()` | `useForm()` |
|
|
801
|
+
| State created above the form | `useForm()` | `useFormStore()` |
|
|
802
|
+
| Errors from the server | written by hand | `error()`, with the browser's |
|