Skip to content

Binding Inputs ​

Writing a Reusable Input ​

useField also takes the name of a field instead of its node, so one input component binds every field:

vue
<script setup lang="ts">
import { provideFormNode, useForm } from '@formtree/vue'
import { contactForm } from './forms/contact-form'
import TextField from './text-field.vue'

const form = useForm(contactForm)
provideFormNode(form)
</script>

<template>
  <TextField name="name" label="Name" />
  <TextField name="email" label="Email" />
  <TextField name="message" label="Message" />
</template>
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

const props = defineProps<{ name: string; label: string }>()

const field = useField<string>(() => props.name)
</script>

<template>
  <div>
    <label :for="field.id">{{ label }}</label>
    <input v-model="field.model" v-bind="field.attrs" />
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </div>
</template>

useField looks the name up in the node that provideFormNode makes available to the components below it. FieldView lists what it returns.

useForm Provides Nothing

useForm only creates the form, so useField with a name throws until a component above calls provideFormNode. Splitting into Components explains why.

useField also takes the name of a field instead of its node, so one input component binds every field:

tsx
import { FormNodeProvider, useForm } from '@formtree/react'
import { contactForm } from './forms/contact-form'
import { TextField } from './text-field'

export function ContactForm() {
  const form = useForm(contactForm)

  return (
    <FormNodeProvider node={form}>
      <TextField name="name" label="Name" />
      <TextField name="email" label="Email" />
      <TextField name="message" label="Message" />
    </FormNodeProvider>
  )
}
tsx
import { useField } from '@formtree/react'

export function TextField({ name, label }: { name: string; label: string }) {
  const field = useField<string>(name)

  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <input
        {...field.attrs}
        value={field.value ?? ''}
        onChange={event => field.setValue(event.target.value)}
      />
      <p id={field.errorId}>{field.errorMessage}</p>
    </div>
  )
}

useField looks the name up in the node that <FormNodeProvider> makes available to the components below it. FieldView lists what it returns.

useForm Provides Nothing

useForm only creates the form, so useField with a name throws until a component above renders <FormNodeProvider>. Splitting into Components explains why.

Moved into a module of its own and given the node of a field, bindInput binds every input of every form:

ts
import { createForm } from '@formtree/core'
import { bindInput } from './bind-input'
import { contactForm } from './forms/contact-form'

const form = createForm(contactForm, { id: 'contact' })

bindInput(form.field('name'))
bindInput(form.field('email'))
bindInput(form.field('message'))
ts
import type { FieldAttributes, FieldNode } from '@formtree/core'

type TextInput = HTMLInputElement | HTMLTextAreaElement

export function bindInput(field: FieldNode<string | undefined, unknown>) {
  const input = document.getElementById(field.id) as TextInput
  const error = document.getElementById(field.errorId)!

  input.addEventListener('input', () => field.setValue(input.value))
  input.addEventListener('blur', () => field.blur())
  showField()
  return field.subscribe(showField)

  function showField() {
    input.value = field.state.value ?? ''
    error.textContent = field.errorMessage ?? ''
    setAttributes(input, field.attributes)
  }
}

export function setAttributes(element: Element, attributes: FieldAttributes) {
  for (const [attribute, value] of Object.entries(attributes)) {
    if (value == null) {
      element.removeAttribute(attribute)
    } else {
      element.setAttribute(attribute, value)
    }
  }
}
html
<label for="contact:name">Name</label>
<input id="contact:name" />
<p id="contact:name:error"></p>

<label for="contact:email">Email</label>
<input id="contact:email" />
<p id="contact:email:error"></p>

<label for="contact:message">Message</label>
<textarea id="contact:message"></textarea>
<p id="contact:message:error"></p>

bindInput calls showField whenever the field changes and returns the function that stops it. showField writes the value, the error, and the attributes of the input, so a reset reaches the page and a screen reader announces the error with the input.

Marking Required Fields ​

state.required is true when the schema of a field rejects an empty value, so the label can mark it:

text-field.vue
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

const props = defineProps<{ name: string; label: string }>()

const field = useField<string>(() => props.name)
</script>

<template>
  <div>
    <label :for="field.id">
      {{ label }}<span v-if="field.state.required" aria-hidden="true">*</span>
    </label>
    <input v-model="field.model" v-bind="field.attrs" />
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </div>
</template>
text-field.tsx
tsx
import { useField } from '@formtree/react'

export function TextField({ name, label }: { name: string; label: string }) {
  const field = useField<string>(name)

  return (
    <div>
      <label htmlFor={field.id}>
        {label}
        {field.state.required && <span aria-hidden="true">*</span>}
      </label>
      <input
        {...field.attrs}
        value={field.value ?? ''}
        onChange={event => field.setValue(event.target.value)}
      />
      <p id={field.errorId}>{field.errorMessage}</p>
    </div>
  )
}
bind-input.ts
ts
export function bindInput(field: FieldNode<string | undefined, unknown>) {
  const input = document.getElementById(field.id) as TextInput
  const error = document.getElementById(field.errorId)!

  input.addEventListener('input', () => field.setValue(input.value))
  input.addEventListener('blur', () => field.blur())
  showField()
  return field.subscribe(showField)

  function showField() {
    input.value = field.state.value ?? ''
    error.textContent = field.errorMessage ?? ''
    input.labels?.[0]?.classList.toggle('required', field.state.required)
    setAttributes(input, field.attributes)
  }
}

A CSS rule such as .required::after { content: '*' } turns the class into an asterisk.

The attributes of the input already carry aria-required, so a screen reader announces the field as required.

What Counts as Required

The schema is asked once, with the form empty, so typing never asks it again. A part that activeWhen activates is marked while it is active, but a key that another answer in the same schema requires is not. Neither is a field that the validate rule of a group requires, or one whose schema answers asynchronously.

Binding a Number Input ​

A number input converts its text in both directions and writes undefined when it is empty:

number-field.vue
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'
import { computed } from 'vue'

const props = defineProps<{ name: string; label: string }>()

const field = useField<number>(() => props.name)

const text = computed({
  get: () => (field.model == undefined ? '' : String(field.model)),
  set: value => {
    field.model = value === '' ? undefined : Number(value)
  },
})
</script>

<template>
  <div>
    <label :for="field.id">{{ label }}</label>
    <input v-model="text" v-bind="field.attrs" type="number" />
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </div>
</template>
number-field.tsx
tsx
import { useField } from '@formtree/react'

interface NumberFieldProps {
  name: string
  label: string
}

export function NumberField({ name, label }: NumberFieldProps) {
  const field = useField<number>(name)

  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <input
        {...field.attrs}
        type="number"
        value={field.value ?? ''}
        onChange={event => field.setValue(toNumber(event.target.value))}
      />
      <p id={field.errorId}>{field.errorMessage}</p>
    </div>
  )
}

function toNumber(text: string) {
  return text == '' ? undefined : Number(text)
}
bind-number-input.ts
ts
import type { FieldNode } from '@formtree/core'
import { setAttributes } from './bind-input'

export function bindNumberInput(
  field: FieldNode<number | undefined, unknown>,
) {
  const input = document.getElementById(field.id) as HTMLInputElement
  const error = document.getElementById(field.errorId)!

  input.addEventListener('input', () => field.setValue(readNumber()))
  input.addEventListener('blur', () => field.blur())
  showField()
  return field.subscribe(showField)

  function showField() {
    if (readNumber() != field.state.value) {
      input.value =
        field.state.value == undefined ? '' : String(field.state.value)
    }
    error.textContent = field.errorMessage ?? ''
    setAttributes(input, field.attributes)
  }

  function readNumber() {
    return input.value == '' ? undefined : Number(input.value)
  }
}

The comparison in showField leaves a number that the user is still typing alone.

Clearing the input empties the field instead of writing 0.

Binding a Select ​

A select starts with a disabled option for the empty field, so nothing looks chosen before the user picks:

select-field.vue
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

interface SelectOption {
  readonly value: string
  readonly label: string
}

const props = defineProps<{
  name: string
  label: string
  options: ReadonlyArray<SelectOption>
}>()

const field = useField<string>(() => props.name)
</script>

<template>
  <div>
    <label :for="field.id">{{ label }}</label>
    <select v-model="field.model" v-bind="field.attrs">
      <option :value="undefined" disabled>Choose…</option>
      <option
        v-for="option in options"
        :key="option.value"
        :value="option.value"
      >
        {{ option.label }}
      </option>
    </select>
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </div>
</template>
select-field.tsx
tsx
import { useField } from '@formtree/react'

interface SelectOption {
  readonly value: string
  readonly label: string
}

interface SelectFieldProps {
  readonly name: string
  readonly label: string
  readonly options: ReadonlyArray<SelectOption>
}

export function SelectField({ name, label, options }: SelectFieldProps) {
  const field = useField<string>(name)

  return (
    <div>
      <label htmlFor={field.id}>{label}</label>
      <select
        {...field.attrs}
        value={field.value ?? ''}
        onChange={event => field.setValue(event.target.value)}
      >
        <option value="" disabled>
          Choose…
        </option>
        {options.map(option => (
          <option key={option.value} value={option.value}>
            {option.label}
          </option>
        ))}
      </select>
      <p id={field.errorId}>{field.errorMessage}</p>
    </div>
  )
}
ts
import type { FieldNode } from '@formtree/core'
import { setAttributes } from './bind-input'

export function bindSelect<Value extends string>(
  field: FieldNode<Value | undefined, unknown>,
  choices: ReadonlyArray<Value>,
) {
  const select = document.getElementById(field.id) as HTMLSelectElement
  const error = document.getElementById(field.errorId)!

  select.addEventListener('change', () =>
    field.setValue(choices.find(choice => choice == select.value)),
  )
  select.addEventListener('blur', () => field.blur())
  showField()
  return field.subscribe(showField)

  function showField() {
    select.value = field.state.value ?? ''
    error.textContent = field.errorMessage ?? ''
    setAttributes(select, field.attributes)
  }
}
html
<label for="account:role">Role</label>
<select id="account:role">
  <option value="" disabled selected>Choose…</option>
  <option value="member">Member</option>
  <option value="admin">Admin</option>
</select>
<p id="account:role:error"></p>

choices turns the selected text back into one of the values of the field, as in bindSelect(form.field('role'), Object.values(ROLE)).

Binding a Checkbox ​

A checkbox reads and writes checked instead of value:

checkbox-field.vue
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

const props = defineProps<{ name: string; label: string }>()

const field = useField<boolean>(() => props.name)
</script>

<template>
  <div>
    <input v-model="field.model" v-bind="field.attrs" type="checkbox" />
    <label :for="field.id">{{ label }}</label>
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </div>
</template>
checkbox-field.tsx
tsx
import { useField } from '@formtree/react'

interface CheckboxFieldProps {
  name: string
  label: string
}

export function CheckboxField({ name, label }: CheckboxFieldProps) {
  const field = useField<boolean>(name)

  return (
    <div>
      <input
        {...field.attrs}
        type="checkbox"
        checked={field.value ?? false}
        onChange={event => field.setValue(event.target.checked)}
      />
      <label htmlFor={field.id}>{label}</label>
      <p id={field.errorId}>{field.errorMessage}</p>
    </div>
  )
}
bind-checkbox.ts
ts
import type { FieldNode } from '@formtree/core'
import { setAttributes } from './bind-input'

export function bindCheckbox(field: FieldNode<true | undefined, unknown>) {
  const checkbox = document.getElementById(field.id) as HTMLInputElement
  const error = document.getElementById(field.errorId)!

  checkbox.addEventListener('change', () =>
    field.setValue(checkbox.checked ? true : undefined),
  )
  checkbox.addEventListener('blur', () => field.blur())
  showField()
  return field.subscribe(showField)

  function showField() {
    checkbox.checked = field.state.value ?? false
    error.textContent = field.errorMessage ?? ''
    setAttributes(checkbox, field.attributes)
  }
}

Required Boxes

A box the user must tick, such as accepting the terms, takes only true, so an unticked box leaves the field empty.

Checkbox Group binds several boxes to one list.

Binding Radio Buttons ​

Radio buttons share one value, so the attributes of the field go on the group around them:

radio-field.vue
vue
<script setup lang="ts">
import { useField } from '@formtree/vue'

const props = defineProps<{
  name: string
  label: string
  options: ReadonlyArray<{ value: string; label: string }>
}>()

const field = useField<string>(() => props.name)
</script>

<template>
  <fieldset v-bind="field.attrs" role="radiogroup" tabindex="-1">
    <legend>{{ label }}</legend>
    <label v-for="option in options" :key="option.value">
      <input
        v-model="field.model"
        type="radio"
        :name="field.attrs.name"
        :value="option.value"
        @blur="field.attrs.onBlur"
      />
      {{ option.label }}
    </label>
    <p :id="field.errorId">{{ field.errorMessage }}</p>
  </fieldset>
</template>
radio-field.tsx
tsx
import { useField } from '@formtree/react'

interface RadioFieldProps {
  name: string
  label: string
  options: ReadonlyArray<{ value: string; label: string }>
}

export function RadioField({ name, label, options }: RadioFieldProps) {
  const field = useField<string>(name)

  return (
    <fieldset {...field.attrs} role="radiogroup" tabIndex={-1}>
      <legend>{label}</legend>
      {options.map(option => (
        <label key={option.value}>
          <input
            type="radio"
            name={field.attrs.name}
            value={option.value}
            checked={field.value == option.value}
            onChange={() => field.setValue(option.value)}
            onBlur={field.attrs.onBlur}
          />
          {option.label}
        </label>
      ))}
      <p id={field.errorId}>{field.errorMessage}</p>
    </fieldset>
  )
}
bind-radio-group.ts
ts
import type { FieldNode } from '@formtree/core'
import { setAttributes } from './bind-input'

export function bindRadioGroup(
  field: FieldNode<string | undefined, unknown>,
) {
  const group = document.getElementById(field.id) as HTMLFieldSetElement
  const radios = group.querySelectorAll<HTMLInputElement>('[type="radio"]')
  const error = document.getElementById(field.errorId)!

  for (const radio of radios) {
    radio.addEventListener('change', () => field.setValue(radio.value))
    radio.addEventListener('blur', () => field.blur())
  }
  showField()
  return field.subscribe(showField)

  function showField() {
    for (const radio of radios) {
      radio.checked = radio.value == field.state.value
    }
    error.textContent = field.errorMessage ?? ''
    setAttributes(group, field.attributes)
  }
}

The group holds the id of the field and tabindex="-1", so a failed submit can focus it, and role="radiogroup" lets screen readers announce its error with it. Every radio shares the name of the field, so only one of them is checked at a time. Radio Group shows this live.

Typing a Binding ​

A name cannot tell TypeScript what its field holds, but a node can. When a field is bound by its node, TypeScript rejects a value that the schema does not accept:

ts
const 
form
=
useForm
(
accountForm
)
const
role
=
useField
(
form
.
field
('role'))
role.model = 'owner'
Type '"owner"' is not assignable to type '"member" | "admin" | undefined'.
tsx
const form = useForm(accountForm)
const role = useField(form.field('role'))

role.setValue('owner')
ts
const 
form
=
createForm
(
accountForm
)
const
role
=
form
.
field
('role')
role
.
setValue
('owner')
Argument of type '"owner"' is not assignable to parameter of type '"member" | "admin" | undefined'.

Released under the MIT License.