Open History to see the last commit
1---
2id: ssr
3title: React Meta-Framework Usage
4---
5β
6TanStack Form is compatible with React out of the box, supporting `SSR` and being framework-agnostic. However, specific configurations are necessary, according to your chosen framework.
7β
8Today we support the following meta-frameworks:
9β
10- [TanStack Start](https://tanstack.com/start/)
11- [Next.js](https://nextjs.org/)
12- [Remix](https://remix.run)
13β
14## Using TanStack Form in TanStack Start
15β
16This section focuses on integrating TanStack Form with TanStack Start.
17β
18### TanStack Start Prerequisites
19β
20- Start a new `TanStack Start` project, following the steps in the [TanStack Start Quickstart Guide](https://tanstack.com/router/latest/docs/framework/react/guide/tanstack-start)
21- Install `@tanstack/react-form`
22β
23### Start integration
24β
25Let's start by creating a `formOption` that we'll use to share the form's shape across the client and server.
26β
27```typescript
28// app/routes/index.tsx, but can be extracted to any other path
29import { formOptions } from '@tanstack/react-form-start'
30β
31// You can pass other form options here
32export const formOpts = formOptions({
33 defaultValues: {
34 firstName: '',
35 age: 0,
36 },
37})
38```
39β
40Next, we can create [a Start Server Function](https://tanstack.com/start/latest/docs/framework/react/server-functions) that will handle the form submission on the server.
41β
42```typescript
43// app/routes/index.tsx, but can be extracted to any other path
44import {
45 createServerValidate,
46 ServerValidateError,
47} from '@tanstack/react-form-start'
48β
49const serverValidate = createServerValidate({
50 ...formOpts,
51 onServerValidate: ({ value }) => {
52 if (value.age < 12) {
53 return 'Server validation: You must be at least 12 to sign up'
54 }
55 },
56})
57β
58export const handleForm = createServerFn({
59 method: 'POST',
60})
61 .inputValidator((data: unknown) => {
62 if (!(data instanceof FormData)) {
63 throw new Error('Invalid form data')
64 }
65 return data
66 })
67 .handler(async (ctx) => {
68 try {
69 const validatedData = await serverValidate(ctx.data)
70 console.log('validatedData', validatedData)
71 // Persist the form data to the database
72 // await sql`
73 // INSERT INTO users (name, email, password)
74 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
75 // `
76 } catch (e) {
77 if (e instanceof ServerValidateError) {
78 // Log form errors or do any other logic here
79 return e.response
80 }
81β
82 // Some other error occurred when parsing the form
83 console.error(e)
84 setResponseStatus(500)
85 return 'There was an internal error'
86 }
87β
88 return 'Form has validated successfully'
89 })
90```
91β
92Then we need to establish a way to grab the form data from `serverValidate`'s `response` using another server action:
93β
94```typescript
95// app/routes/index.tsx, but can be extracted to any other path
96import { getFormData } from '@tanstack/react-form-start'
97β
98export const getFormDataFromServer = createServerFn({ method: 'GET' }).handler(
99 async () => {
100 return getFormData()
101 },
102)
103```
104β
105Finally, we'll use `getFormDataFromServer` in our loader to get the state from our server into our client and `handleForm` in our client-side form component.
106β
107```tsx
108// app/routes/index.tsx
109import { createFileRoute } from '@tanstack/react-router'
110import {
111 mergeForm,
112 useForm,
113 useStore,
114 useTransform,
115} from '@tanstack/react-form-start'
116β
117export const Route = createFileRoute('/')({
118 component: Home,
119 loader: async () => ({
120 state: await getFormDataFromServer(),
121 }),
122})
123β
124function Home() {
125 const { state } = Route.useLoaderData()
126 const form = useForm({
127 ...formOpts,
128 transform: useTransform((baseForm) => mergeForm(baseForm, state), [state]),
129 })
130β
131 const formErrors = useStore(form.store, (formState) => formState.errors)
132β
133 return (
134 <form action={handleForm.url} method="post" encType={'multipart/form-data'}>
135 {formErrors.map((error) => (
136 <p key={error as string}>{error}</p>
137 ))}
138β
139 <form.Field
140 name="age"
141 validators={{
142 onChange: ({ value }) =>
143 value < 8 ? 'Client validation: You must be at least 8' : undefined,
144 }}
145 >
146 {(field) => {
147 return (
148 <div>
149 <input
150 name={field.name}
151 type="number"
152 value={field.state.value}
153 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
154 />
155 {field.state.meta.errors.map((error) => (
156 <p key={error as string}>{error}</p>
157 ))}
158 </div>
159 )
160 }}
161 </form.Field>
162 <form.Subscribe
163 selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
164 >
165 {([canSubmit, isSubmitting]) => (
166 <button type="submit" disabled={!canSubmit}>
167 {isSubmitting ? '...' : 'Submit'}
168 </button>
169 )}
170 </form.Subscribe>
171 </form>
172 )
173}
174```
175β
176## Using TanStack Form in a Next.js App Router
177β
178> Before reading this section, it's suggested you understand how React Server Components and React Server Actions work. [Check out this blog series for more information](https://playfulprogramming.com/collections/react-beyond-the-render)
179β
180This section focuses on integrating TanStack Form with `Next.js`, particularly using the `App Router` and `Server Actions`.
181β
182### Next.js Prerequisites
183β
184- Start a new `Next.js` project, following the steps in the [Next.js Documentation](https://nextjs.org/docs/getting-started/installation). Ensure you select `yes` for `Would you like to use App Router?` during the setup to access all new features provided by Next.js.
185- Install `@tanstack/react-form`
186- Install any [form validator](./validation#validation-through-schema-libraries) of your choice. [Optional]
187β
188## App Router integration
189β
190Let's start by creating a `formOption` that we'll use to share the form's shape across the client and server.
191β
192```typescript
193// shared-code.ts
194// Notice the import path is different from the client
195import { formOptions } from '@tanstack/react-form-nextjs'
196β
197// You can pass other form options here
198export const formOpts = formOptions({
199 defaultValues: {
200 firstName: '',
201 age: 0,
202 },
203})
204```
205β
206Next, we can create [a React Server Action](https://playfulprogramming.com/posts/what-are-react-server-components) that will handle the form submission on the server.
207β
208```typescript
209// action.ts
210'use server'
211β
212// Notice the import path is different from the client
213import {
214 ServerValidateError,
215 createServerValidate,
216} from '@tanstack/react-form-nextjs'
217import { formOpts } from './shared-code'
218β
219// Create the server action that will infer the types of the form from `formOpts`
220const serverValidate = createServerValidate({
221 ...formOpts,
222 onServerValidate: ({ value }) => {
223 if (value.age < 12) {
224 return 'Server validation: You must be at least 12 to sign up'
225 }
226 },
227})
228β
229export default async function someAction(prev: unknown, formData: FormData) {
230 try {
231 const validatedData = await serverValidate(formData)
232 console.log('validatedData', validatedData)
233 // Persist the form data to the database
234 // await sql`
235 // INSERT INTO users (name, email, password)
236 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
237 // `
238 } catch (e) {
239 if (e instanceof ServerValidateError) {
240 return e.formState
241 }
242β
243 // Some other error occurred while validating your form
244 throw e
245 }
246β
247 // Your form has successfully validated!
248}
249```
250β
251Finally, we'll use `someAction` in our client-side form component.
252β
253```tsx
254// client-component.tsx
255'use client'
256β
257import { useActionState } from 'react'
258import {
259 initialFormState,
260 mergeForm,
261 useForm,
262 useStore,
263 useTransform,
264} from '@tanstack/react-form-nextjs'
265import someAction from './action'
266import { formOpts } from './shared-code'
267β
268export const ClientComp = () => {
269 const [state, action] = useActionState(someAction, initialFormState)
270β
271 const form = useForm({
272 ...formOpts,
273 transform: useTransform((baseForm) => mergeForm(baseForm, state!), [state]),
274 })
275β
276 const formErrors = useStore(form.store, (formState) => formState.errors)
277β
278 return (
279 <form action={action as never} onSubmit={() => form.handleSubmit()}>
280 {formErrors.map((error) => (
281 <p key={error as string}>{error}</p>
282 ))}
283β
284 <form.Field
285 name="age"
286 validators={{
287 onChange: ({ value }) =>
288 value < 8 ? 'Client validation: You must be at least 8' : undefined,
289 }}
290 >
291 {(field) => {
292 return (
293 <div>
294 <input
295 name={field.name} // must explicitly set the name attribute for the POST request
296 type="number"
297 value={field.state.value}
298 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
299 />
300 {field.state.meta.errors.map((error) => (
301 <p key={error as string}>{error}</p>
302 ))}
303 </div>
304 )
305 }}
306 </form.Field>
307 <form.Subscribe
308 selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
309 >
310 {([canSubmit, isSubmitting]) => (
311 <button type="submit" disabled={!canSubmit}>
312 {isSubmitting ? '...' : 'Submit'}
313 </button>
314 )}
315 </form.Subscribe>
316 </form>
317 )
318}
319```
320β
321Here, we're using [React's `useActionState` hook](https://playfulprogramming.com/posts/what-is-use-action-state-and-form-status) and TanStack Form's `useTransform` hook to merge state returned from the server action with the form state.
322β
323> If you get the following error in your Next.js application:
324>
325> ```typescript
326> x You're importing a component that needs `useState`. This React hook only works in a client component. To fix, mark the file (or its parent) with the `"use client"` directive.
327> ```
328>
329> This is because you're not importing server-side code from `@tanstack/react-form-nextjs`. Ensure you're importing the correct module based on the environment.
330>
331> [This is a limitation of Next.js](https://github.com/phryneas/rehackt). Other meta-frameworks will likely not have this same problem.
332β
333## Using TanStack Form in Remix
334β
335> Before reading this section, it's suggested you understand how Remix actions work. [Check out Remix's docs for more information](https://remix.run/docs/en/main/discussion/data-flow#route-action)
336β
337### Remix Prerequisites
338β
339- Start a new `Remix` project, following the steps in the [Remix Documentation](https://remix.run/docs/en/main/start/quickstart).
340- Install `@tanstack/react-form`
341- Install any [form validator](./validation#validation-through-schema-libraries) of your choice. [Optional]
342β
343## Remix integration
344β
345Let's start by creating a `formOption` that we'll use to share the form's shape across the client and server.
346β
347```typescript
348// routes/_index/route.tsx
349import { formOptions } from '@tanstack/react-form-remix'
350β
351// You can pass other form options here
352export const formOpts = formOptions({
353 defaultValues: {
354 firstName: '',
355 age: 0,
356 },
357})
358```
359β
360Next, we can create [an action](https://remix.run/docs/en/main/discussion/data-flow#route-action) that will handle the form submission on the server.
361β
362```tsx
363// routes/_index/route.tsx
364β
365import {
366 ServerValidateError,
367 createServerValidate,
368 formOptions,
369} from '@tanstack/react-form-remix'
370β
371import type { ActionFunctionArgs } from '@remix-run/node'
372β
373// export const formOpts = formOptions({
374β
375// Create the server action that will infer the types of the form from `formOpts`
376const serverValidate = createServerValidate({
377 ...formOpts,
378 onServerValidate: ({ value }) => {
379 if (value.age < 12) {
380 return 'Server validation: You must be at least 12 to sign up'
381 }
382 },
383})
384β
385export async function action({ request }: ActionFunctionArgs) {
386 const formData = await request.formData()
387 try {
388 const validatedData = await serverValidate(formData)
389 console.log('validatedData', validatedData)
390 // Persist the form data to the database
391 // await sql`
392 // INSERT INTO users (name, email, password)
393 // VALUES (${validatedData.name}, ${validatedData.email}, ${validatedData.password})
394 // `
395 } catch (e) {
396 if (e instanceof ServerValidateError) {
397 return e.formState
398 }
399β
400 // Some other error occurred while validating your form
401 throw e
402 }
403β
404 // Your form has successfully validated!
405}
406```
407β
408Finally, the `action` will be called when the form submits.
409β
410```tsx
411// routes/_index/route.tsx
412import {
413 Form,
414 mergeForm,
415 useActionData,
416 useForm,
417 useStore,
418 useTransform,
419} from '@tanstack/react-form'
420import {
421 ServerValidateError,
422 createServerValidate,
423 formOptions,
424 initialFormState,
425} from '@tanstack/react-form-remix'
426β
427import type { ActionFunctionArgs } from '@remix-run/node'
428β
429// export const formOpts = formOptions({
430β
431// const serverValidate = createServerValidate({
432β
433// export async function action({request}: ActionFunctionArgs) {
434β
435export default function Index() {
436 const actionData = useActionData<typeof action>()
437β
438 const form = useForm({
439 ...formOpts,
440 transform: useTransform(
441 (baseForm) => mergeForm(baseForm, actionData ?? initialFormState),
442 [actionData],
443 ),
444 })
445β
446 const formErrors = useStore(form.store, (formState) => formState.errors)
447β
448 return (
449 <Form method="post" onSubmit={() => form.handleSubmit()}>
450 {formErrors.map((error) => (
451 <p key={error as string}>{error}</p>
452 ))}
453β
454 <form.Field
455 name="age"
456 validators={{
457 onChange: ({ value }) =>
458 value < 8 ? 'Client validation: You must be at least 8' : undefined,
459 }}
460 >
461 {(field) => {
462 return (
463 <div>
464 <input
465 name="age"
466 type="number"
467 value={field.state.value}
468 onChange={(e) => field.handleChange(e.target.valueAsNumber)}
469 />
470 {field.state.meta.errors.map((error) => (
471 <p key={error as string}>{error}</p>
472 ))}
473 </div>
474 )
475 }}
476 </form.Field>
477 <form.Subscribe
478 selector={(formState) => [formState.canSubmit, formState.isSubmitting]}
479 >
480 {([canSubmit, isSubmitting]) => (
481 <button type="submit" disabled={!canSubmit}>
482 {isSubmitting ? '...' : 'Submit'}
483 </button>
484 )}
485 </form.Subscribe>
486 </Form>
487 )
488}
489```
490β
491Here, we're using [Remix's `useActionData` hook](https://remix.run/docs/en/main/hooks/use-action-data) and TanStack Form's `useTransform` hook to merge state returned from the server action with the form state.