Writing a widget
A widget is the React component a registration renders for one field. It binds to the form with useFormField, and the one choice it makes is how the control holds its value.
| The control is | Call | The field renders |
|---|---|---|
A native input, textarea or select | useFormField(config) | For an error, a warning or a flag, never for a keystroke. |
A component that takes only value and onChange props | useFormField(config, { controlled: true }) | Whenever its value changes. |
Uncontrolled is the default. The DOM holds what the user types and a keystroke writes to the container without rendering anything. Spread fieldProps on the control (ref, id, name, required, disabled, aria-*, onChange(event) and onBlur()) and give it defaultValue, which is frozen when the field mounts and is the server's value while the form hydrates. A checkbox takes defaultChecked, and a radio group takes defaultChecked={defaultValue === option} on each radio, all sharing fieldProps.
Controlled is for a component with no native element to read: a Radix, Base UI or react-aria checkbox, select or slider, a date picker, a phone input, a drop zone. It takes value, onChange(value) and onBlur(). fieldProps keeps its ref, which focuses the control and reports the browser's verdict when it lands on a native element.
Both modes are in this file: a text field that is uncontrolled, a rating that is controlled and a submit button.
import * as z from 'zod/mini';
import { createFormEngine, defineInput } from '@schema-engine/forms';
import { BaseFieldSchema } from '@schema-engine/forms/schemas/base-field';
import { fieldText, useFormField } from '@schema-engine/forms-react/hooks';
const TextSchema = z.extend(BaseFieldSchema, { $type: z.literal('text') });
/** A native control: uncontrolled, so a keystroke renders nothing. */
function TextField(config: z.output<typeof TextSchema>) {
const { defaultValue, error, fieldProps, labelProps, errorProps } = useFormField(config);
return (
<div>
<label {...labelProps}>{config.label}</label>
<input {...fieldProps} defaultValue={fieldText(defaultValue)} />
{errorProps && <p {...errorProps}>{error}</p>}
</div>
);
}
const RatingSchema = z.extend(BaseFieldSchema, { $type: z.literal('rating'), max: z._default(z.number(), 5) });
/** A component that takes `value` and `onChange`: controlled, so it renders with its value. */
function RatingField(config: z.output<typeof RatingSchema>) {
const { value, onChange, onBlur, fieldProps, error, errorProps } = useFormField(config, { controlled: true });
return (
<div role="radiogroup" aria-label={config.label} onBlur={onBlur}>
{Array.from({ length: config.max }, (_, index) => index + 1).map((star) => (
<button
key={star}
type="button"
ref={star === 1 ? fieldProps.ref : undefined}
aria-pressed={value === star}
onClick={() => onChange(star)}
>
{star}
</button>
))}
{errorProps && <p {...errorProps}>{error}</p>}
</div>
);
}
const SubmitSchema = z.extend(BaseFieldSchema, { $type: z.literal('submit') });
function SubmitButton(config: z.output<typeof SubmitSchema>) {
return <button type="submit">{config.label}</button>;
}
const TextRegistration = defineInput({
$type: 'text',
schema: TextSchema,
render: TextField,
metadata: { name: 'Text', category: 'input' },
});
const RatingRegistration = defineInput({
$type: 'rating',
schema: RatingSchema,
render: RatingField,
metadata: { name: 'Rating', category: 'input' },
});
const SubmitRegistration = defineInput({
$type: 'submit',
schema: SubmitSchema,
render: SubmitButton,
metadata: { name: 'Submit', category: 'input' },
});
export const engine = createFormEngine({ elements: [TextRegistration, RatingRegistration, SubmitRegistration] });What the form does for an uncontrolled field
- It reads the control. Text from
.value, a checkbox from.checked(a checkbox with avalueattribute adds or removes that value in an array), a radio group from the checked radio, aselect multiplefrom its selected options, a number input fromvalueAsNumberand a file input from its files. - It writes changes back. A reset,
setValuein code or a row update writes into the control through itsref, and only when the control would read differently. A keystroke is never echoed back, the cursor stays, an IME composition is safe and a number input that holds1eis left alone. File inputs are only cleared. - Rows keep their elements. On a row move the
refre-registers under the new path and nothing is written. - Text typed before hydration is kept. If the control differs from what React rendered when its
refattaches, the container takes it. - A native reset button goes through
container.reset(), so the screen and the values cannot disagree. - It reports native validity when the
reflands on an input, select or textarea. See Native validity.
In development, an uncontrolled field whose ref lands on something that is not an input, select or textarea logs a warning that names { controlled: true }.
Which registry widget uses which
| Widget | Mode |
|---|---|
| input, textarea | Uncontrolled |
| field array shell | Binds no control: a keystroke in a row does not render it |
| checkbox, checkbox group, switch, radio, select, combobox, number, slider, date, date range, phone, masked, OTP, drop zone | Controlled |
The other hooks
| Hook | Returns |
|---|---|
useFormField('contacts.0.email') | The state and texts of a path (a field, an array or FORM_ROOT), with no value. |
useWatch(path) | The value at a path. useWatch() is every value, and useWatch([a, b]) is the values in order. |
useFieldArray('contacts') | fields and append, prepend, insert, swap, move, update, replace and remove. Adding a row focuses it. |
useFormContext() | getValues, setValue, validate, reset, setFocus, formatIssue, clearSubmission and a lazy formState. |
formState (errors, isValid, submission) is read lazily: a component re-renders only for the keys it reads, so a submit button that reads submission.status does not render while the user types. See Hooks for the full reference.
Values are unknown, so a text control passes its default through fieldText(value), which gives the text a text control shows.