@rsc-kit/mcp 0.40.0 → 0.42.0
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 +37 -20
- 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 -250
- package/guides/bap-vs-inertia.md +67 -25
- package/guides/blueprints.md +307 -174
- package/guides/bun.md +42 -25
- package/guides/caching.md +46 -49
- package/guides/coming-from-inertia.md +5 -5
- 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 -538
- 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 +251 -218
- 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 +272 -150
- 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 -538
- package/guides/laravel.md +0 -786
- package/guides/your-own-backend.md +0 -587
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={ordersCreate}>
|
|
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 = appsCreate.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,217 +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
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const [optimisticTodos, addOptimistic] = useOptimistic(
|
|
253
|
-
todos,
|
|
254
|
-
(state, newTodo: Todo) => [...state, newTodo]
|
|
255
|
-
);
|
|
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
|
+
```
|
|
256
185
|
|
|
257
|
-
|
|
258
|
-
<div>
|
|
259
|
-
<ul>
|
|
260
|
-
{optimisticTodos.map((todo) => (
|
|
261
|
-
<li key={todo.id}>{todo.title}</li>
|
|
262
|
-
))}
|
|
263
|
-
</ul>
|
|
186
|
+
The names come from:
|
|
264
187
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
>
|
|
271
|
-
<input name="title" />
|
|
272
|
-
<button>Add</button>
|
|
273
|
-
</Form>
|
|
274
|
-
</div>
|
|
275
|
-
);
|
|
276
|
-
}
|
|
277
|
-
```
|
|
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.
|
|
278
192
|
|
|
279
|
-
|
|
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`.
|
|
280
197
|
|
|
281
|
-
|
|
198
|
+
### Typing a wrapper around an action
|
|
282
199
|
|
|
283
|
-
|
|
284
|
-
|
|
200
|
+
A function of `FormData` could read anything, so it names no fields. Declare
|
|
201
|
+
them on its parameter with `FormFields`:
|
|
285
202
|
|
|
286
|
-
|
|
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
|
-
|
|
305
|
-
|
|
306
|
-
When the form's `action` is the page the visitor is already on, there is no other page whose shell could stand in while the query runs: the shell would be this page with nothing in it. So the form does not show one. The page stays on screen, results and all, and the new results replace the old ones when they arrive. The input keeps what was typed, a Suspense boundary that was already showing its content keeps showing it instead of falling back to its skeleton, and Back returns to the query the visitor left.
|
|
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`.
|
|
307
217
|
|
|
308
|
-
|
|
218
|
+
### Binding an argument first
|
|
309
219
|
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
import { Form } from "@rsc-kit/core/form";
|
|
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:
|
|
314
222
|
|
|
315
|
-
|
|
316
|
-
|
|
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
|
-
underneath, and Radix renders a hidden native control whenever you give it a
|
|
372
|
-
`name`, for exactly this. Omit the `name` and it is invisible to the form; that
|
|
373
|
-
is the only thing to remember.
|
|
374
|
-
|
|
375
|
-
:::caution[Not shadcn's own `<Form>`]
|
|
376
|
-
shadcn's `<Form>`, `<FormField>` and `<FormControl>` are wrappers around
|
|
377
|
-
[react-hook-form](https://react-hook-form.com), which is a different system for
|
|
378
|
-
the same job — its own state, its own validation, its own submit. Use one or
|
|
379
|
-
the other, not both.
|
|
380
|
-
|
|
381
|
-
Ours gives you the field errors the *server* returned, which is the half a
|
|
382
|
-
client-side library cannot do.
|
|
383
|
-
:::
|
|
384
|
-
|
|
385
|
-
### shadcn's `Field` components
|
|
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.
|
|
386
248
|
|
|
387
|
-
|
|
388
|
-
presentational components — they take props rather than reading a form
|
|
389
|
-
library's context, which is what the older `<FormField>` did. So they work here
|
|
390
|
-
directly:
|
|
249
|
+
A component below the form types its prop with `FieldNamesOf`:
|
|
391
250
|
|
|
392
251
|
```tsx
|
|
393
|
-
|
|
394
|
-
{({ pending, error }) => (
|
|
395
|
-
<FieldGroup>
|
|
396
|
-
<Field data-invalid={!!error('title')}>
|
|
397
|
-
<FieldLabel htmlFor="title">Bug title</FieldLabel>
|
|
398
|
-
<Input id="title" name="title" aria-invalid={!!error('title')} />
|
|
399
|
-
<FieldDescription>Keep it short and specific.</FieldDescription>
|
|
400
|
-
<FieldError>{error('title')}</FieldError>
|
|
401
|
-
</Field>
|
|
252
|
+
import type { FieldNamesOf } from '@rsc-kit/core/form'
|
|
402
253
|
|
|
403
|
-
|
|
404
|
-
{pending ? 'Sending…' : 'Submit'}
|
|
405
|
-
</Button>
|
|
406
|
-
</FieldGroup>
|
|
407
|
-
)}
|
|
408
|
-
</Form>
|
|
254
|
+
type Props = { name: FieldNamesOf<typeof orders.create> }
|
|
409
255
|
```
|
|
410
256
|
|
|
411
|
-
|
|
412
|
-
so `error('title')` goes straight in. Everything else is the same markup you
|
|
413
|
-
would write with any other form library.
|
|
257
|
+
## Setting the values
|
|
414
258
|
|
|
415
|
-
|
|
416
|
-
react-hook-form those are the *client's* validation; here `error()` answers with
|
|
417
|
-
the client's **and** whatever the server sent back, because a refused action
|
|
418
|
-
returns its fields rather than throwing them away.
|
|
419
|
-
|
|
420
|
-
### Setting the values
|
|
421
|
-
|
|
422
|
-
The fields are uncontrolled, so an initial value is `defaultValue` — React's
|
|
423
|
-
own, nothing of ours:
|
|
259
|
+
An initial value is React's own `defaultValue`:
|
|
424
260
|
|
|
425
261
|
```tsx
|
|
426
262
|
<Input id="title" name="title" defaultValue={post.title} />
|
|
427
263
|
```
|
|
428
264
|
|
|
429
|
-
After a refused submit the values are still there, because
|
|
430
|
-
|
|
431
|
-
not owning the value.
|
|
265
|
+
After a refused submit the values are still there, because nothing re-rendered
|
|
266
|
+
the inputs.
|
|
432
267
|
|
|
433
|
-
The exception is a submit
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
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`.
|
|
437
271
|
|
|
438
|
-
|
|
272
|
+
## How the values are read
|
|
439
273
|
|
|
440
|
-
|
|
441
|
-
is not there at all — a fact that used to leak into every schema as
|
|
442
|
-
`z.coerce.number()` and a per-checkbox `.transform()`. It does not any more.
|
|
443
|
-
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:
|
|
444
275
|
|
|
445
276
|
```ts
|
|
446
277
|
const settings = z.object({
|
|
@@ -459,29 +290,31 @@ const settings = z.object({
|
|
|
459
290
|
})
|
|
460
291
|
```
|
|
461
292
|
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
`boolean` is `false
|
|
466
|
-
`number` is the number
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
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.
|
|
485
318
|
|
|
486
319
|
### Lists of values
|
|
487
320
|
|
|
@@ -493,17 +326,16 @@ A repeated name is an array:
|
|
|
493
326
|
// → { tags: ['react', 'vite'] }
|
|
494
327
|
```
|
|
495
328
|
|
|
496
|
-
With one ticked that is `'react'`,
|
|
497
|
-
|
|
498
|
-
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:
|
|
499
331
|
|
|
500
332
|
```tsx
|
|
501
333
|
<Checkbox name="tags[]" value="react" />
|
|
502
334
|
// → { tags: ['react'] }
|
|
503
335
|
```
|
|
504
336
|
|
|
505
|
-
The brackets are dropped from the key, and
|
|
506
|
-
|
|
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.
|
|
507
339
|
|
|
508
340
|
### Nested and repeating groups
|
|
509
341
|
|
|
@@ -515,11 +347,10 @@ Names that describe a shape build it:
|
|
|
515
347
|
<input name="items[0][name]" /> // the same field, other spelling
|
|
516
348
|
```
|
|
517
349
|
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
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')`.
|
|
521
352
|
|
|
522
|
-
Rows you add and remove are ordinary state
|
|
353
|
+
Rows you add and remove are ordinary state. Only the names have to line up:
|
|
523
354
|
|
|
524
355
|
```tsx
|
|
525
356
|
{rows.map((row, i) => (
|
|
@@ -527,85 +358,43 @@ Rows you add and remove are ordinary state; only the *names* have to line up:
|
|
|
527
358
|
))}
|
|
528
359
|
```
|
|
529
360
|
|
|
530
|
-
|
|
361
|
+
## When fields are checked
|
|
531
362
|
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
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.
|
|
535
366
|
|
|
536
|
-
|
|
537
|
-
|
|
367
|
+
The form listens for `focusout` itself, so a plain `<Input name="title" />` is
|
|
368
|
+
covered without binding it.
|
|
538
369
|
|
|
539
|
-
|
|
540
|
-
<Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
|
|
541
|
-
{({ field, error }) => (
|
|
542
|
-
<Field data-invalid={!!error('description')}>
|
|
543
|
-
<FieldLabel htmlFor="description">Description</FieldLabel>
|
|
370
|
+
### Checking with the server before submit
|
|
544
371
|
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
</InputGroup>
|
|
551
|
-
|
|
552
|
-
<FieldError>{error('description')}</FieldError>
|
|
553
|
-
</Field>
|
|
554
|
-
)}
|
|
555
|
-
</Form>
|
|
556
|
-
```
|
|
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.
|
|
557
377
|
|
|
558
|
-
|
|
559
|
-
`<Controller>` does, for the same reason.
|
|
378
|
+
There's nothing to turn on. The actions that can be asked:
|
|
560
379
|
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
### When a field is checked
|
|
570
|
-
|
|
571
|
-
**A field is checked when it is left, not as it is typed.** An error that
|
|
572
|
-
appears while someone is halfway through an email address is a form arguing
|
|
573
|
-
with them; leaving the field is the moment they have finished saying what they
|
|
574
|
-
meant. So `error()` has nothing for a field nobody has reached yet, and there is
|
|
575
|
-
no separate "touched" to consult before showing it.
|
|
576
|
-
|
|
577
|
-
It works on ordinary uncontrolled fields too — the form listens for `focusout`
|
|
578
|
-
rather than each field listening for `blur`, so `<Input name="title" />` is
|
|
579
|
-
covered without being bound to anything.
|
|
580
|
-
|
|
581
|
-
### Checked by the server before it is submitted
|
|
582
|
-
|
|
583
|
-
A schema in the browser cannot know that an email is already subscribed, or
|
|
584
|
-
that a coupon has expired. The server can, and `<Form>` asks it: when a field
|
|
585
|
-
is left **having changed**, the form sends what it holds to the action marked
|
|
586
|
-
as a check. The action's guards and validation run for that field; the action
|
|
587
|
-
itself does not. Its answer lands on `error()` like any other.
|
|
588
|
-
|
|
589
|
-
Nothing to opt into. Which actions can be asked:
|
|
590
|
-
|
|
591
|
-
- a `createActionClient()` action with an input schema - its middleware and
|
|
592
|
-
schema run, its handler is skipped;
|
|
593
|
-
- a backend function the backend says it can check without running - in
|
|
594
|
-
Laravel, any action whose first parameter is a form request (its
|
|
595
|
-
`authorize()` and `rules()`, filtered to the field, as Laravel's
|
|
596
|
-
Precognition does);
|
|
597
|
-
- 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
|
|
598
387
|
body, so it is never called to check, and the form stops asking after the
|
|
599
388
|
first answer says so.
|
|
600
389
|
|
|
601
|
-
A field the browser's schema already refuses
|
|
602
|
-
|
|
603
|
-
|
|
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.
|
|
604
393
|
|
|
605
394
|
#### When a blur is not the moment
|
|
606
395
|
|
|
607
|
-
`validate()` asks now, about the fields you name
|
|
608
|
-
|
|
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:
|
|
609
398
|
|
|
610
399
|
```tsx
|
|
611
400
|
<Form action={register}>
|
|
@@ -631,19 +420,18 @@ It resolves `true` when they pass. That is a wizard's step:
|
|
|
631
420
|
</Form>
|
|
632
421
|
```
|
|
633
422
|
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
`*` stands for one segment of a nested name, as in Laravel: `validate('items.*.sku')`.
|
|
638
|
-
For a field checked as it is typed, call `validate('handle')` from its
|
|
639
|
-
`onChange` - and debounce it yourself; the form does not decide how often you
|
|
640
|
-
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.
|
|
641
425
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
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.
|
|
645
433
|
|
|
646
|
-
|
|
434
|
+
## After a successful submit
|
|
647
435
|
|
|
648
436
|
```tsx
|
|
649
437
|
{({ succeeded, recentlySucceeded }) => (
|
|
@@ -651,12 +439,10 @@ not for deciding anything.
|
|
|
651
439
|
)}
|
|
652
440
|
```
|
|
653
441
|
|
|
654
|
-
`recentlySucceeded` is
|
|
655
|
-
and fades.
|
|
656
|
-
because the timer has to be cleared when the component goes away and that is
|
|
657
|
-
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.
|
|
658
444
|
|
|
659
|
-
|
|
445
|
+
## Disabling save until something changes
|
|
660
446
|
|
|
661
447
|
```tsx
|
|
662
448
|
{({ dirty, reset }) => (
|
|
@@ -667,42 +453,49 @@ the part people forget.
|
|
|
667
453
|
)}
|
|
668
454
|
```
|
|
669
455
|
|
|
670
|
-
`dirty` is whether
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
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.
|
|
459
|
+
|
|
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.
|
|
462
|
+
|
|
463
|
+
## Controlling one field
|
|
464
|
+
|
|
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:
|
|
680
467
|
|
|
681
|
-
|
|
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>
|
|
682
473
|
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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>
|
|
687
480
|
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
481
|
+
<FieldError>{error('description')}</FieldError>
|
|
482
|
+
</Field>
|
|
483
|
+
)}
|
|
484
|
+
</Form>
|
|
485
|
+
```
|
|
691
486
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
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.
|
|
696
491
|
|
|
697
|
-
|
|
698
|
-
controlled opt-in costs: `field()` is a function call rather than a render prop,
|
|
699
|
-
which keeps the markup flat and means a bound field re-renders this component
|
|
700
|
-
rather than only itself.
|
|
492
|
+
Bind only the fields that need it and leave the rest alone.
|
|
701
493
|
|
|
702
|
-
|
|
703
|
-
one or two, for a character count or a control with no native element.
|
|
494
|
+
### In its own component
|
|
704
495
|
|
|
705
|
-
|
|
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:
|
|
706
499
|
|
|
707
500
|
```tsx
|
|
708
501
|
import { useField } from '@rsc-kit/core/form'
|
|
@@ -714,19 +507,9 @@ function Title() {
|
|
|
714
507
|
}
|
|
715
508
|
```
|
|
716
509
|
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
`useField` re-renders **that component and nothing else** — not the form, not
|
|
720
|
-
its siblings. Which is what `<Controller>` achieves with a render prop, except
|
|
721
|
-
that the component you were going to write anyway is the boundary.
|
|
722
|
-
|
|
723
|
-
So the scoping is there when a form is large enough to need it, and the flat
|
|
724
|
-
markup is there when it is not.
|
|
725
|
-
|
|
726
|
-
### Reading the values from elsewhere
|
|
510
|
+
### Reading a value from elsewhere
|
|
727
511
|
|
|
728
|
-
A preview, a summary
|
|
729
|
-
field — reads it the same way the field does:
|
|
512
|
+
A preview, a summary or a count reads a value the same way:
|
|
730
513
|
|
|
731
514
|
```tsx
|
|
732
515
|
function Preview() {
|
|
@@ -736,27 +519,12 @@ function Preview() {
|
|
|
736
519
|
}
|
|
737
520
|
```
|
|
738
521
|
|
|
739
|
-
Only a
|
|
740
|
-
|
|
741
|
-
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.
|
|
742
524
|
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
and a submit button outside it is `form="the-id"`.
|
|
747
|
-
|
|
748
|
-
Worth knowing what the alternatives do here, because it is not as different as
|
|
749
|
-
it looks. Reaching a form from another component is a context in all three:
|
|
750
|
-
react-hook-form has `<FormProvider>` and `useFormContext()`, and TanStack Form
|
|
751
|
-
has `createFormHookContexts()` with `useFormContext()` — which its own
|
|
752
|
-
documentation calls a bridge for integration constraints, to be avoided when
|
|
753
|
-
passing the form as a prop is possible. Ours needs no extra provider only
|
|
754
|
-
because `<Form>` already is one.
|
|
755
|
-
|
|
756
|
-
Where they are genuinely more flexible is *where the state is created*: their
|
|
757
|
-
`useForm()` is called by you, so it can be hoisted as far up as you like. For
|
|
758
|
-
the case where that matters — something that is not a descendant — create the
|
|
759
|
-
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:
|
|
760
528
|
|
|
761
529
|
```tsx
|
|
762
530
|
function Page() {
|
|
@@ -777,44 +545,258 @@ function TopBar({ store }) {
|
|
|
777
545
|
}
|
|
778
546
|
```
|
|
779
547
|
|
|
780
|
-
`useFormStore`
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
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:
|
|
634
|
+
|
|
635
|
+
```tsx title="SearchForm.tsx"
|
|
636
|
+
"use client";
|
|
784
637
|
|
|
785
|
-
|
|
786
|
-
|
|
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.
|
|
787
740
|
:::
|
|
788
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
|
+
|
|
789
770
|
## It works before hydration
|
|
790
771
|
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
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
|
-
|
|
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 |
|