Splitting into Components
Connecting Components to a Form
Four functions connect components to a form, and each does one thing:
| Function | What it does |
|---|---|
useForm(definition) | Creates a form that lives as long as the component. It provides nothing. |
provideFormNode(node) | Makes a node, the form or one of its parts, available to every component below. |
useField(node) | Binds a field that the component already holds to an input. |
useField(name) | Finds the field by name in the nearest provided node, and binds it. |
useFormNode(definition) | Returns the nearest provided node of that definition, typed by it. |
Nothing is provided on its own, so a form that only its own component reads needs no provideFormNode, as in the Introduction. A form that components below read is provided once, by the component that creates it. useField(name) and useFormNode throw when no component above provided a node.
Three hooks and one component connect components to a form, and each does one thing:
| Function | What it does |
|---|---|
useForm(definition) | Creates a form that lives as long as the component. It provides nothing. |
<FormNodeProvider node={node}> | Makes a node, the form or one of its parts, available to every component below. |
useField(node) | Binds a field that the component already holds to an input. |
useField(name) | Finds the field by name in the nearest provided node, and binds it. |
useFormNode(definition) | Returns the nearest provided node of that definition, typed by it, without re-rendering. |
Nothing is provided on its own, so a form that only its own component reads needs no <FormNodeProvider>, as in the Introduction. A form that components below read is provided once, by the component that creates it. useField(name) and useFormNode throw when no component above provided a node.
Without components, nothing is provided. A function that works on a part of the form receives its node as an argument, as the sections below show.
Why useForm Provides Nothing
The component that creates a form decides which components see it, and which node they see. It can provide a single step instead of the whole form, and two forms on one page never compete for the same slot. A component below reads only what its ancestors chose to provide.
Using a Part in a Component
A component below the one that provides the form gets its part with useFormNode, which takes the definition of the node it wants:
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { orderForm } from './forms/order'
import TextField from './text-field.vue'
provideFormNode(useFormNode(orderForm).group('contact'))
</script>
<template>
<TextField name="fullName" label="Name" />
<TextField name="email" label="Email" />
</template>The section provides the contact details in turn, so its inputs bind by names relative to them.
No Fallback
useFormNode throws when no ancestor provided a node of that definition.
A component below the one that provides the form gets its part with useFormNode, which takes the definition of the node it wants:
import { FormNodeProvider, useFormNode } from '@formtree/react'
import { orderForm } from './forms/order'
import { TextField } from './text-field'
export function ContactSection() {
const contact = useFormNode(orderForm).group('contact')
return (
<FormNodeProvider node={contact}>
<TextField name="fullName" label="Name" />
<TextField name="email" label="Email" />
</FormNodeProvider>
)
}The section provides the contact details in turn, so its inputs bind by names relative to them.
No Fallback
useFormNode throws when no ancestor provided a node of that definition.
Each part is set up in a function that takes the node of the part, typed with NodeOf from its definition:
import type { NodeOf } from '@formtree/core'
import { createForm } from '@formtree/core'
import { bindInput } from './bind-input'
import { contactGroup } from './forms/contact'
import { orderForm } from './forms/order'
const form = createForm(orderForm)
bindContactSection(form.group('contact'))
function bindContactSection(contact: NodeOf<typeof contactGroup>) {
bindInput(contact.field('fullName'))
bindInput(contact.field('email'))
}The function knows only the contact definition, so it works for contact details in any form.
Rendering Rows
The list renders one row component per item, keyed by the key of the item, and passes it the index of the item:
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { orderForm } from './forms/order'
import LineItemRow from './line-item-row.vue'
const lineItems = provideFormNode(useFormNode(orderForm).array('lineItems'))
</script>
<template>
<LineItemRow
v-for="lineItem in lineItems.items"
:key="lineItem.key"
:index="lineItem.index"
/>
</template>The row reads the list by its definition and provides its item:
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { lineItemsArray } from './forms/line-items'
import NumberField from './number-field.vue'
import TextField from './text-field.vue'
const props = defineProps<{ index: number }>()
provideFormNode(useFormNode(lineItemsArray).items[props.index]!)
</script>
<template>
<TextField name="sku" label="Product" />
<NumberField name="quantity" label="Quantity" />
</template>Keyed by key, each component stays with its item when the list is reordered.
The list reads its items with useNodeState, renders one row component per item, keyed by the key of the item, and passes it the index of the item:
import { FormNodeProvider, useFormNode, useNodeState } from '@formtree/react'
import { orderForm } from './forms/order'
import { LineItemRow } from './line-item-row'
export function LineItemList() {
const lineItems = useFormNode(orderForm).array('lineItems')
const items = useNodeState(lineItems, node => node.items)
return (
<FormNodeProvider node={lineItems}>
{items.map(lineItem => (
<LineItemRow key={lineItem.key} index={lineItem.index} />
))}
</FormNodeProvider>
)
}The list re-renders when a row is added, removed, or moved, not when a value inside a row changes. The row reads the list by its definition and provides its item:
import { FormNodeProvider, useFormNode } from '@formtree/react'
import { lineItemsArray } from './forms/line-items'
import { NumberField } from './number-field'
import { TextField } from './text-field'
export function LineItemRow({ index }: { index: number }) {
const row = useFormNode(lineItemsArray).items[index]!
return (
<FormNodeProvider node={row}>
<TextField name="sku" label="Product" />
<NumberField name="quantity" label="Quantity" />
</FormNodeProvider>
)
}Keyed by key, each component stays with its item when the list is reordered.
The element of each row is created once and kept by the key of its item:
import type { ArrayItem, NodeOf } from '@formtree/core'
import { createForm } from '@formtree/core'
import { lineItemGroup } from './forms/line-items'
import { orderForm } from './forms/order'
const form = createForm(orderForm)
const lineItems = form.array('lineItems')
const list = document.getElementById('line-items')!
const rowTemplate = document.getElementById(
'line-item-row',
) as HTMLTemplateElement
const rowElements = new Map<string, HTMLElement>()
renderRows()
function renderRows() {
list.replaceChildren(
...lineItems.items.map(lineItem => {
const element = rowElements.get(lineItem.key) ?? createRow(lineItem)
rowElements.set(lineItem.key, element)
return element
}),
)
}
function createRow(row: NodeOf<typeof lineItemGroup> & ArrayItem) {
const blankRow = rowTemplate.content.firstElementChild!
const element = blankRow.cloneNode(true) as HTMLElement
element.querySelector('.remove')!.addEventListener('click', () => {
rowElements.delete(row.key)
lineItems.remove(row.index)
renderRows()
})
return element
}Each element stays with its item when the list is reordered, and row.index is always the current position of the item.
Showing the State of a Row
The template reads row.state to show what the row is doing, such as a save in progress:
<script setup lang="ts">
import { provideFormNode, useFormNode } from '@formtree/vue'
import { saveLineItem } from './api'
import { lineItemsArray } from './forms/line-items'
import NumberField from './number-field.vue'
import TextField from './text-field.vue'
const props = defineProps<{ index: number }>()
const row = provideFormNode(useFormNode(lineItemsArray).items[props.index]!)
const save = row.handleSubmit(async lineItem => {
await saveLineItem(lineItem)
})
</script>
<template>
<TextField name="sku" label="Product" />
<NumberField name="quantity" label="Quantity" />
<button type="button" :aria-busy="row.state.submitting" @click="save">
{{ row.state.submitting ? 'Saving…' : 'Save' }}
</button>
</template>state is reactive, so the button updates when the save starts and when it ends.
useNodeState reads submitting and re-renders the component only when the value it selects changes:
import { FormNodeProvider, useFormNode, useNodeState } from '@formtree/react'
import { saveLineItem } from './api'
import { lineItemsArray } from './forms/line-items'
import { NumberField } from './number-field'
import { TextField } from './text-field'
export function LineItemRow({ index }: { index: number }) {
const row = useFormNode(lineItemsArray).items[index]!
const submitting = useNodeState(row, node => node.state.submitting)
const save = row.handleSubmit(async lineItem => {
await saveLineItem(lineItem)
})
return (
<FormNodeProvider node={row}>
<TextField name="sku" label="Product" />
<NumberField name="quantity" label="Quantity" />
<button type="button" aria-busy={submitting} onClick={() => save()}>
{submitting ? 'Saving…' : 'Save'}
</button>
</FormNodeProvider>
)
}A component re-renders only through useNodeState and useField, so reading row.state directly would show the state from the last render.
The row updates itself from its own subscribe to show what it is doing, such as a save in progress:
function createRow(row: NodeOf<typeof lineItemGroup> & ArrayItem) {
const blankRow = rowTemplate.content.firstElementChild!
const element = blankRow.cloneNode(true) as HTMLElement
const save = element.querySelector<HTMLButtonElement>('.save')!
save.addEventListener(
'click',
row.handleSubmit(async lineItem => {
await saveLineItem(lineItem)
}),
)
const stopShowingStatus = row.subscribe(() => {
save.textContent = row.state.submitting ? 'Saving…' : 'Save'
save.setAttribute('aria-busy', String(row.state.submitting))
})
element.querySelector('.remove')!.addEventListener('click', () => {
stopShowingStatus()
rowElements.delete(row.key)
lineItems.remove(row.index)
renderRows()
})
return element
}Removing the row stops its subscription.