As you create more forms, you start to handle them the same way each time. For example, we may have an invalid submission handler that isn't tied to any particular form:
const form = useForm({
defaultValues: { firstName: '' },
validators: [/* ... */],
onSubmitInvalid: ({ reason, preventThrow }) => {
preventThrow()
if (reason === 'validation') {
// Focus on the first invalid input element
document.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus()
}
},
})We can create a custom function and pass it to every form hook, but we still have to remember to do so.
That's where form composition comes in: it reduces UI boilerplate and, in our case, lets us set default options.
Let's use the function above as a default:
import { createFormHook } from '@tanstack/react-form'
export const { useAppForm, appFormOptions, defineAppFieldGroup } =
createFormHook({
fieldComponents: {/* See guide for Field components */},
formComponents: {/* See guide for Form components */},
defaultOptions: {
// Default options for useForm
forms: {
onSubmitInvalid: ({ reason, preventThrow }) => {
preventThrow()
if (reason === 'validation') {
document
.querySelector<HTMLElement>('[aria-invalid="true"]')
?.focus()
}
},
},
// Default options for <form.FormGroup />
formGroups: {
onSubmitInvalid: ({ reason, preventThrow }) => {
preventThrow()
if (reason === 'validation') {
document
.querySelector<HTMLElement>('[aria-invalid="true"]')
?.focus()
}
},
},
},
})The form hook supports UI components, but for now, we'll focus on the three functions it returns. These replace the following:
| Normal | Form hook variant |
|---|---|
| useForm | useAppForm |
| formOptions | appFormOptions |
| defineFieldGroup | defineAppFieldGroup |
In a component, we can now use the form hook:
const form = useAppForm({
defaultValues: { firstName: '' },
validators: [/* ... */],
// Invalid submissions are handled automatically now
})If a particular form needs to handle invalid submissions differently, you can define its handler in useAppForm:
const form = useAppForm({
defaultValues: { firstName: '' },
validators: [/* ... */],
onSubmitInvalid: ({ preventThrow }) => {
preventThrow()
// This form is on a page that uses toast messages
toast('Could not submit!')
},
})If you need to opt out of the default altogether, you can also provide undefined:
const form = useAppForm({
defaultValues: { firstName: '' },
validators: [/* ... */],
// Do not apply the default option
onSubmitInvalid: undefined,
})Sometimes, you may want to keep the default option when adding a local option. For example, consider a default listener that logs data:
import { createFormHook } from '@tanstack/react-form'
const { useAppForm } = createFormHook({
fieldComponents: {},
formComponents: {},
defaultOptions: {
forms: {
listeners: [
{
run: ({ value }) => {
console.log('Value changed:', value)
},
triggers: ['change'],
triggerDebounceMs: 500,
},
],
},
},
})However, with this setup, adding local form listeners would replace the default listener:
const form = useAppForm({
defaultValues: { firstName: '' },
listeners: [
{
triggers: ['change'],
run: () => {
console.log('Oops! The default logger was lost.')
},
},
],
})To control how local options combine with defaults, you can choose from three behaviors:
Let's configure the default logging listener to come before local listeners:
import { createFormHook } from '@tanstack/react-form'
const { useAppForm } = createFormHook({
fieldComponents: {},
formComponents: {},
defaultOptions: {
forms: {
// Use an object with `value` and `behaviour` instead of passing the array directly
listeners: {
// The listener code can stay as-is.
value: [
{
run: ({ value }) => {
console.log('Value changed:', value)
},
triggers: ['change'],
triggerDebounceMs: 500,
},
],
// If local listeners are used, the form will use
// [...defaultListeners, ...localListeners]
behaviour: 'defaultFirst',
},
},
},
})