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

overview.md

842 lines23.6 KB

1---
2id: overview
3title: Overview
4---
5​
6TanStack Form is the ultimate solution for handling forms in web applications, providing a powerful and flexible approach to form management. Designed with first-class TypeScript support, headless UI components, and a framework-agnostic design, it streamlines form handling and ensures a seamless experience across various front-end frameworks.
7​
8## Motivation
9​
10Most web frameworks do not offer a comprehensive solution for form handling, leaving developers to create their own custom implementations or rely on less-capable libraries. This often results in a lack of consistency, poor performance, and increased development time. TanStack Form aims to address these challenges by providing an all-in-one solution for managing forms that is both powerful and easy to use.
11​
12With TanStack Form, developers can tackle common form-related challenges such as:
13​
14- Reactive data binding and state management
15- Complex validation and error handling
16- Accessibility and responsive design
17- Internationalization and localization
18- Cross-platform compatibility and custom styling
19​
20By providing a complete solution for these challenges, TanStack Form empowers developers to build robust and user-friendly forms with ease.
21​
22## Enough talk, show me some code already!
23​
24<!-- ::start:framework -->
25​
26# React
27​
28In the example below, you can see TanStack Form in action with the React framework adapter:
29​
30[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/react/simple)
31​
32<!-- ::start:tabs variant="files" -->
33​
34```tsx title="App.tsx"
35import * as React from 'react'
36import { createRoot } from 'react-dom/client'
37import { TanStackDevtools } from '@tanstack/react-devtools'
38import { formDevtoolsPlugin } from '@tanstack/react-form-devtools'
39import { useForm } from '@tanstack/react-form'
40​
41import { FieldInfo } from './FieldInfo.tsx'
42​
43export default function App() {
44 const form = useForm({
45 defaultValues: {
46 firstName: '',
47 lastName: '',
48 },
49 onSubmit: async ({ value }) => {
50 // Do something with form data
51 console.log(value)
52 },
53 })
54​
55 return (
56 <div>
57 <h1>Simple Form Example</h1>
58 <form
59 onSubmit={(e) => {
60 e.preventDefault()
61 e.stopPropagation()
62 form.handleSubmit()
63 }}
64 >
65 <div>
66 {/* A type-safe field component*/}
67 <form.Field
68 name="firstName"
69 validators={{
70 onChange: ({ value }) =>
71 !value
72 ? 'A first name is required'
73 : value.length < 3
74 ? 'First name must be at least 3 characters'
75 : undefined,
76 onChangeAsyncDebounceMs: 500,
77 onChangeAsync: async ({ value }) => {
78 await new Promise((resolve) => setTimeout(resolve, 1000))
79 return (
80 value.includes('error') && 'No "error" allowed in first name'
81 )
82 },
83 }}
84 children={(field) => {
85 // Avoid hasty abstractions. Render props are great!
86 return (
87 <>
88 <label htmlFor={field.name}>First Name:</label>
89 <input
90 id={field.name}
91 name={field.name}
92 value={field.state.value}
93 onBlur={field.handleBlur}
94 onChange={(e) => field.handleChange(e.target.value)}
95 />
96 <FieldInfo field={field} />
97 </>
98 )
99 }}
100 />
101 </div>
102 <div>
103 <form.Field
104 name="lastName"
105 children={(field) => (
106 <>
107 <label htmlFor={field.name}>Last Name:</label>
108 <input
109 id={field.name}
110 name={field.name}
111 value={field.state.value}
112 onBlur={field.handleBlur}
113 onChange={(e) => field.handleChange(e.target.value)}
114 />
115 <FieldInfo field={field} />
116 </>
117 )}
118 />
119 </div>
120 <form.Subscribe
121 selector={(state) => [state.canSubmit, state.isSubmitting]}
122 children={([canSubmit, isSubmitting]) => (
123 <>
124 <button type="submit" disabled={!canSubmit}>
125 {isSubmitting ? '...' : 'Submit'}
126 </button>
127 <button
128 type="reset"
129 onClick={(e) => {
130 // Avoid unexpected resets of form elements (especially <select> elements)
131 e.preventDefault()
132 form.reset()
133 }}
134 >
135 Reset
136 </button>
137 </>
138 )}
139 />
140 </form>
141 </div>
142 )
144​
145const rootElement = document.getElementById('root')!
146​
147createRoot(rootElement).render(
148 <React.StrictMode>
149 <App />
150​
151 <TanStackDevtools
152 config={{ hideUntilHover: true }}
153 plugins={[formDevtoolsPlugin()]}
154 />
155 </React.StrictMode>,
157```
158​
159```tsx title="FieldInfo.tsx"
160import type { AnyFieldApi } from '@tanstack/react-form'
161​
162export function FieldInfo({ field }: { field: AnyFieldApi }) {
163 return (
164 <>
165 {field.state.meta.isTouched && !field.state.meta.isValid ? (
166 <em>{field.state.meta.errors.join(',')}</em>
167 ) : null}
168 {field.state.meta.isValidating ? 'Validating...' : null}
169 </>
170 )
172```
173​
174<!-- ::end:tabs -->
175​
176# Vue
177​
178In the example below, you can see TanStack Form in action with the Vue framework adapter:
179​
180[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/vue/simple)
181​
182<!-- ::start:tabs variant="files" -->
183​
184```vue title="App.vue"
185<script setup lang="ts">
186import { useForm } from '@tanstack/vue-form'
187import FieldInfo from './FieldInfo.vue'
188​
189const form = useForm({
190 defaultValues: {
191 firstName: '',
192 lastName: '',
193 },
194 onSubmit: async ({ value }) => {
195 // Do something with form data
196 alert(JSON.stringify(value))
197 },
198})
199​
200async function onChangeFirstName({ value }: { value: string }) {
201 await new Promise((resolve) => setTimeout(resolve, 1000))
202 return value.includes(`error`) && `No 'error' allowed in first name`
204</script>
205​
206<template>
207 <form
208 @submit="
209 (e) => {
210 e.preventDefault()
211 e.stopPropagation()
212 form.handleSubmit()
213 }
214 "
215 >
216 <div>
217 <form.Field
218 name="firstName"
219 :validators="{
220 onChange: ({ value }) =>
221 !value
222 ? `A first name is required`
223 : value.length < 3
224 ? `First name must be at least 3 characters`
225 : undefined,
226 onChangeAsyncDebounceMs: 500,
227 onChangeAsync: onChangeFirstName,
228 }"
229 >
230 <template v-slot="{ field, state }">
231 <label :htmlFor="field.name">First Name:</label>
232 <input
233 :id="field.name"
234 :name="field.name"
235 :value="field.state.value"
236 @input="
237 (e) => field.handleChange((e.target as HTMLInputElement).value)
238 "
239 @blur="field.handleBlur"
240 />
241 <FieldInfo :state="state" />
242 </template>
243 </form.Field>
244 </div>
245 <div>
246 <form.Field name="lastName">
247 <template v-slot="{ field, state }">
248 <label :htmlFor="field.name">Last Name:</label>
249 <input
250 :id="field.name"
251 :name="field.name"
252 :value="field.state.value"
253 @input="
254 (e) => field.handleChange((e.target as HTMLInputElement).value)
255 "
256 @blur="field.handleBlur"
257 />
258 <FieldInfo :state="state" />
259 </template>
260 </form.Field>
261 </div>
262 <form.Subscribe>
263 <template v-slot="{ canSubmit, isSubmitting }">
264 <button type="submit" :disabled="!canSubmit">
265 {{ isSubmitting ? '...' : 'Submit' }}
266 </button>
267 </template>
268 </form.Subscribe>
269 </form>
270</template>
271```
272​
273```vue title="FieldInfo.vue"
274<script setup lang="ts">
275import { AnyFieldApi } from '@tanstack/vue-form'
276​
277const props = defineProps<{
278 state: AnyFieldApi['state']
279}>()
280</script>
281​
282<template>
283 <template v-if="props.state.meta.isTouched">
284 <em v-for="error of props.state.meta.errors">{{ error }}</em>
285 {{ props.state.meta.isValidating ? 'Validating...' : null }}
286 </template>
287</template>
288```
289​
290<!-- ::end:tabs -->
291​
292# Angular
293​
294In the example below, you can see TanStack Form in action with the Angular framework adapter:
295​
296[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/angular/simple)
297​
298<!-- ::start:tabs variant="files" -->
299​
300```angular-ts title="app.component.ts"
301import { Component } from '@angular/core'
302import { TanStackField, injectForm, injectStore } from '@tanstack/angular-form'
303import type {
304 FieldValidateAsyncFn,
305 FieldValidateFn,
306} from '@tanstack/angular-form'
307​
308@Component({
309 selector: 'app-root',
310 standalone: true,
311 imports: [TanStackField],
312 template: `
313 <form (submit)="handleSubmit($event)">
314 <div>
315 <ng-container
316 [tanstackField]="form"
317 name="firstName"
318 [validators]="{
319 onChange: firstNameValidator,
320 onChangeAsyncDebounceMs: 500,
321 onChangeAsync: firstNameAsyncValidator,
322 }"
323 #firstName="field"
324 >
325 <label [for]="firstName.api.name">First Name:</label>
326 <input
327 [id]="firstName.api.name"
328 [name]="firstName.api.name"
329 [value]="firstName.api.state.value"
330 (blur)="firstName.api.handleBlur()"
331 (input)="firstName.api.handleChange($any($event).target.value)"
332 />
333 @if (firstName.api.state.meta.isTouched) {
334 @for (error of firstName.api.state.meta.errors; track $index) {
335 <div style="color: red">
336 {{ error }}
337 </div>
338 }
339 }
340 @if (firstName.api.state.meta.isValidating) {
341 <p>Validating...</p>
342 }
343 </ng-container>
344 </div>
345 <div>
346 <ng-container [tanstackField]="form" name="lastName" #lastName="field">
347 <label [for]="lastName.api.name">Last Name:</label>
348 <input
349 [id]="lastName.api.name"
350 [name]="lastName.api.name"
351 [value]="lastName.api.state.value"
352 (blur)="lastName.api.handleBlur()"
353 (input)="lastName.api.handleChange($any($event).target.value)"
354 />
355 </ng-container>
356 </div>
357 <button type="submit" [disabled]="!canSubmit()">
358 {{ isSubmitting() ? '...' : 'Submit' }}
359 </button>
360 <button type="reset" (click)="form.reset()">Reset</button>
361 </form>
362 `,
363})
364export class AppComponent {
365 firstNameValidator: FieldValidateFn<any, string, any> = ({ value }) =>
366 !value
367 ? 'A first name is required'
368 : value.length < 3
369 ? 'First name must be at least 3 characters'
370 : undefined
371​
372 firstNameAsyncValidator: FieldValidateAsyncFn<any, string, any> = async ({
373 value,
374 }) => {
375 await new Promise((resolve) => setTimeout(resolve, 1000))
376 return value.includes('error') && 'No "error" allowed in first name'
377 }
378​
379 form = injectForm({
380 defaultValues: {
381 firstName: '',
382 lastName: '',
383 },
384 onSubmit({ value }) {
385 // Do something with form data
386 console.log(value)
387 },
388 })
389​
390 canSubmit = injectStore(this.form, (state) => state.canSubmit)
391 isSubmitting = injectStore(this.form, (state) => state.isSubmitting)
392​
393 handleSubmit(event: SubmitEvent) {
394 event.preventDefault()
395 event.stopPropagation()
396 this.form.handleSubmit()
397 }
399```
400​
401<!-- ::end:tabs -->
402​
403# Solid
404​
405In the example below, you can see TanStack Form in action with the Solid framework adapter:
406​
407[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/solid/simple)
408​
409<!-- ::start:tabs variant="files" -->
410​
411```ts title="App.tsx"
412/* @refresh reload */
413import { render } from 'solid-js/web'
414import { createForm } from '@tanstack/solid-form'
415import { FieldInfo } from './FieldInfo.tsx';
416​
417function App() {
418 const form = createForm(() => ({
419 defaultValues: {
420 firstName: '',
421 lastName: '',
422 },
423 onSubmit: async ({ value }) => {
424 // Do something with form data
425 console.log(value)
426 },
427 }))
428​
429 return (
430 <div>
431 <h1>Simple Form Example</h1>
432 <form
433 onSubmit={(e) => {
434 e.preventDefault()
435 e.stopPropagation()
436 form.handleSubmit()
437 }}
438 >
439 <div>
440 {/* A type-safe field component*/}
441 <form.Field
442 name="firstName"
443 validators={{
444 onChange: ({ value }) =>
445 !value
446 ? 'A first name is required'
447 : value.length < 3
448 ? 'First name must be at least 3 characters'
449 : undefined,
450 onChangeAsyncDebounceMs: 500,
451 onChangeAsync: async ({ value }) => {
452 await new Promise((resolve) => setTimeout(resolve, 1000))
453 return (
454 value.includes('error') && 'No "error" allowed in first name'
455 )
456 },
457 }}
458 children={(field) => {
459 // Avoid hasty abstractions. Render props are great!
460 return (
461 <>
462 <label for={field().name}>First Name:</label>
463 <input
464 id={field().name}
465 name={field().name}
466 value={field().state.value}
467 onBlur={field().handleBlur}
468 onInput={(e) => field().handleChange(e.target.value)}
469 />
470 <FieldInfo field={field()} />
471 </>
472 )
473 }}
474 />
475 </div>
476 <div>
477 <form.Field
478 name="lastName"
479 children={(field) => (
480 <>
481 <label for={field().name}>Last Name:</label>
482 <input
483 id={field().name}
484 name={field().name}
485 value={field().state.value}
486 onBlur={field().handleBlur}
487 onInput={(e) => field().handleChange(e.target.value)}
488 />
489 <FieldInfo field={field()} />
490 </>
491 )}
492 />
493 </div>
494 <form.Subscribe
495 selector={(state) => ({
496 canSubmit: state.canSubmit,
497 isSubmitting: state.isSubmitting,
498 })}
499 children={(state) => {
500 return (
501 <button type="submit" disabled={!state().canSubmit}>
502 {state().isSubmitting ? '...' : 'Submit'}
503 </button>
504 )
505 }}
506 />
507 </form>
508 </div>
509 )
511​
512const root = document.getElementById('root')
513​
514render(() => <App />, root!)
515```
516​
517```ts title="FieldInfo.tsx"
518import type { AnyFieldApi } from '@tanstack/solid-form'
519​
520export interface FieldInfoProps {
521 field: AnyFieldApi
523​
524export function FieldInfo(props: FieldInfoProps) {
525 return (
526 <>
527 {props.field.state.meta.isTouched && !props.field.state.meta.isValid ? (
528 <em>{props.field.state.meta.errors.join(',')}</em>
529 ) : null}
530 {props.field.state.meta.isValidating ? 'Validating...' : null}
531 </>
532 )
534```
535​
536<!-- ::end:tabs -->
537​
538# Svelte
539​
540In the example below, you can see TanStack Form in action with the Svelte framework adapter:
541​
542[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/svelte/simple)
543​
544<!-- ::start:tabs variant="files" -->
545​
546```svelte title="App.svelte"
547<script lang="ts">
548 import { createForm } from '@tanstack/svelte-form'
549 import FieldInfo from './FieldInfo.svelte'
550​
551 const form = createForm(() => ({
552 defaultValues: {
553 firstName: '',
554 lastName: '',
555 employed: false,
556 jobTitle: '',
557 },
558 onSubmit: async ({ value }) => {
559 // Do something with form data
560 alert(JSON.stringify(value))
561 },
562 }))
563</script>
564​
565<form
566 id="form"
567 onsubmit={(e) => {
568 e.preventDefault()
569 e.stopPropagation()
570 form.handleSubmit()
571 }}
573 <h1>TanStack Form - Svelte Demo</h1>
574​
575 <form.Field
576 name="firstName"
577 validators={{
578 onChange: ({ value }) =>
579 value.length < 3 ? 'Not long enough' : undefined,
580 onChangeAsyncDebounceMs: 500,
581 onChangeAsync: async ({ value }) => {
582 await new Promise((resolve) => setTimeout(resolve, 1000))
583 return value.includes('error') && 'No "error" allowed in first name'
584 },
585 }}
586 >
587 {#snippet children(field)}
588 <div>
589 <label for={field.name}>First Name</label>
590 <input
591 id={field.name}
592 type="text"
593 placeholder="First Name"
594 value={field.state.value}
595 onblur={() => field.handleBlur()}
596 oninput={(e: Event) => {
597 const target = e.target as HTMLInputElement
598 field.handleChange(target.value)
599 }}
600 />
601 <FieldInfo {field} />
602 </div>
603 {/snippet}
604 </form.Field>
605 <form.Field
606 name="lastName"
607 validators={{
608 onChange: ({ value }) =>
609 value.length < 3 ? 'Not long enough' : undefined,
610 }}
611 >
612 {#snippet children(field)}
613 <div>
614 <label for={field.name}>Last Name</label>
615 <input
616 id={field.name}
617 type="text"
618 placeholder="Last Name"
619 value={field.state.value}
620 onblur={() => field.handleBlur()}
621 oninput={(e: Event) => {
622 const target = e.target as HTMLInputElement
623 field.handleChange(target.value)
624 }}
625 />
626 <FieldInfo {field} />
627 </div>
628 {/snippet}
629 </form.Field>
630 <form.Field name="employed">
631 {#snippet children(field)}
632 <div>
633 <label for={field.name}>Employed?</label>
634 <input
635 oninput={() => field.handleChange(!field.state.value)}
636 checked={field.state.value}
637 onblur={() => field.handleBlur()}
638 id={field.name}
639 type="checkbox"
640 />
641 </div>
642 {#if field.state.value}
643 <form.Field
644 name="jobTitle"
645 validators={{
646 onChange: ({ value }) =>
647 value.length === 0 ? 'If you have a job, you need a title' : null,
648 }}
649 >
650 {#snippet children(field)}
651 <div>
652 <label for={field.name}>Job Title</label>
653 <input
654 type="text"
655 id={field.name}
656 placeholder="Job Title"
657 value={field.state.value}
658 onblur={field.handleBlur}
659 oninput={(e: Event) => {
660 const target = e.target as HTMLInputElement
661 field.handleChange(target.value)
662 }}
663 />
664 <FieldInfo {field} />
665 </div>
666 {/snippet}
667 </form.Field>
668 {/if}
669 {/snippet}
670 </form.Field>
671 <div>
672 <form.Subscribe
673 selector={(state) => ({
674 canSubmit: state.canSubmit,
675 isSubmitting: state.isSubmitting,
676 })}
677 >
678 {#snippet children({ canSubmit, isSubmitting })}
679 <button type="submit" disabled={!canSubmit}>
680 {isSubmitting ? 'Submitting' : 'Submit'}
681 </button>
682 {/snippet}
683 </form.Subscribe>
684 <button
685 type="button"
686 id="reset"
687 onclick={() => {
688 form.reset()
689 }}
690 >
691 Reset
692 </button>
693 </div>
694</form>
695```
696​
697```svelte title="FieldInfo.svelte"
698<script lang="ts">
699 import type { AnyFieldApi } from '@tanstack/svelte-form'
700​
701 let { field }: { field: AnyFieldApi } = $props()
702</script>
703​
704{#if field.state.meta.isTouched}
705 {#each field.state.meta.errors as error}
706 <em>{error}</em>
707 {/each}
708 {field.state.meta.isValidating ? 'Validating...' : ''}
709{/if}
710```
711​
712<!-- ::end:tabs -->
713​
714# Lit
715​
716In the example below, you can see TanStack Form in action with the Lit framework adapter:
717​
718[Open in CodeSandbox](https://codesandbox.io/s/github/tanstack/form/tree/main/examples/lit/simple)
719​
720```ts title="index.ts"
721import { LitElement, html, nothing } from 'lit'
722import { customElement } from 'lit/decorators.js'
723​
724import { TanStackFormController } from '@tanstack/lit-form'
725import { repeat } from 'lit/directives/repeat.js'
726​
727@customElement('tanstack-form-demo')
728export class TanStackFormDemo extends LitElement {
729 #form = new TanStackFormController(this, {
730 defaultValues: {
731 firstName: '',
732 lastName: '',
733 },
734 onSubmit({ value }) {
735 // Do something with form data
736 console.log(value)
737 },
738 })
739​
740 render() {
741 return html`
742 <form
743 @submit=${(e: Event) => {
744 e.preventDefault()
745 e.stopPropagation()
746 this.#form.api.handleSubmit()
747 }}
748 >
749 ${this.#form.field(
750 {
751 name: `firstName`,
752 validators: {
753 onChange: ({ value }) =>
754 !value
755 ? 'A first name is required'
756 : value.length < 3
757 ? 'First name must be at least 3 characters'
758 : undefined,
759 onChangeAsyncDebounceMs: 500,
760 onChangeAsync: async ({ value }) => {
761 await new Promise((resolve) => setTimeout(resolve, 1000))
762 return (
763 value.includes('error') &&
764 'No "error" allowed in first name'
765 )
766 },
767 },
768 },
769 (field) => {
770 return html` <div>
771 <label for="${field.name}">First Name:</label>
772 <input
773 id="${field.name}"
774 name="${field.name}"
775 .value="${field.state.value}"
776 @blur="${() => field.handleBlur()}"
777 @input="${(e: Event) => {
778 const target = e.target as HTMLInputElement
779 field.handleChange(target.value)
780 }}"
781 />
782 ${field.state.meta.isTouched && !field.state.meta.isValid
783 ? html`${repeat(
784 field.state.meta.errors,
785 (__, idx) => idx,
786 (error) => {
787 return html`<div style="color: red;">${error}</div>`
788 },
789 )}`
790 : nothing}
791 ${field.state.meta.isValidating
792 ? html`<p>Validating...</p>`
793 : nothing}
794 </div>`
795 },
796 )}
797 </div>
798 <div>
799 ${this.#form.field(
800 {
801 name: `lastName`,
802 },
803 (field) => {
804 return html` <div>
805 <label for="${field.name}">Last Name:</label>
806 <input
807 id="${field.name}"
808 name="${field.name}"
809 .value="${field.state.value}"
810 @blur="${() => field.handleBlur()}"
811 @input="${(e: Event) => {
812 const target = e.target as HTMLInputElement
813 field.handleChange(target.value)
814 }}"
815 />
816 </div>`
817 },
818 )}
819 </div>
820​
821 <button type="submit" ?disabled=${this.#form.api.state.isSubmitting}>
822 ${this.#form.api.state.isSubmitting ? '...' : 'Submit'}
823 </button>
824 <button
825 type="button"
826 @click=${() => {
827 this.#form.api.reset()
828 }}
829 >
830 Reset
831 </button>
832 </form>
833 `
834 }
836```
837​
838<!-- ::end:framework -->
839​
840## You talked me into it, so what now?
841​
842- Learn TanStack Form at your own pace with our thorough [Walkthrough Guide](./installation) and [API Reference](./reference/classes/FormApi).