use-form-field
Subscribes a component to a value store carried by its onChange handler
Source
Package
Usage
use-form-field subscribes a custom input to a form field through its onChange handler.
A state manager such as useForm attaches a field to the handler it passes down.
The input then rerenders on its own when the field value changes, the component that owns the form does not.
Pass the onChange prop to the hook. When a field is attached, field.subscribed is true
and the component must render field.value. Otherwise, keep using the value prop:
All Mantine inputs and components built with use-uncontrolled already call this hook.
Field protocol
A handler carries a field when a FormField object is stored on it under Symbol.for('mantine-form-field').
Any store can attach it:
onExternalWrite
Some components keep state that the value cannot express. A date input with a partially typed date
reports null until the date is complete. When the store writes null again, the value does not
change and the component cannot know that it has to clear the entry.
onExternalWrite is called with the field value on every write made by the store, not by the component.
It is also called when the component is bound to another field, for example after list items are reordered.
Update only the internal state in the callback, do not call onChange:
Set subscribe: false when the component renders the value prop instead of the subscribed value.
The store then rerenders the component that passes value.
Definition
Exported types
The UseFormFieldOptions, UseFormFieldReturnValue and FormField types are exported from @mantine/hooks:
Usage with @mantine/form
use-form attaches a field to every onChange handler returned by getInputProps.
A custom input that calls use-form-field rerenders alone when its field changes.
Writes made with form methods, for example form.setFieldValue or form.reset, reach onExternalWrite.
With subscribe: false, the form rerenders the component that called useForm instead,
so the input receives a new value prop:
In uncontrolled mode, bind each field path to a single input. A component that is not subscribed does not update while the user types in a subscribed input of the same path. See one input per field path.
See the custom input and rich text form examples.