Form
/ Guides
Form
/ Guides

Non-String Values

By default, useField (and useFormField respectively) expects string values and defaults to an empty string if no initial value is provided.
In order to also support e.g. boolean values or arrays, we can provide custom types.

Note

Passing a custom value type and change event will also change the type of field.value and the expected input for update.

Tip

There's also the formatValue option to convert the value before it's passed to props and inputProps.

const acceptsTerms = useField<boolean, React.ChangeEvent<HTMLInputElement>>(
  z.boolean(),
  {
    // alter how the value is obtained from the change event if neccessary
    // e.g. for checkboxes or custom inputs
    parseEvent: (e) => e.target.checked,
    // set an initial value overwritting the default empty string
    value: false,
  }
)

// custom multi-select input that returns an array of values on change
type Tags = Array<string>
type TagsChangeEvent = (value: Tags) => void

const tags = useField<Tags, TagsChangeEvent>(z.array(z.string()), {
  parseEvent: (value) => value,
  value: [],
})

// also reflects the update and value type
tags.update({
  value: [...tags.value, 'foo'],
})