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 isCallThe field renders
A native input, textarea or selectuseFormField(config)For an error, a warning or a flag, never for a keystroke.
A component that takes only value and onChange propsuseFormField(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, defineStatic, BaseFieldSchema } from '@schema-engine/forms';
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,
	value: () => z.string(),
	metadata: { name: 'Text', category: 'input' },
});

const RatingRegistration = defineInput({
	$type: 'rating',
	schema: RatingSchema,
	render: RatingField,
	value: ({ max }) => z.number().check(z.int(), z.gte(1), z.lte(max)),
	metadata: { name: 'Rating', category: 'input' },
});

const SubmitRegistration = defineStatic({
	$type: 'submit',
	schema: SubmitSchema,
	render: SubmitButton,
	metadata: { name: 'Submit', category: 'action' },
});

export const engine = createFormEngine({ elements: [TextRegistration, RatingRegistration, SubmitRegistration] });

A checkbox and a radio group

A checkbox takes defaultChecked, and a radio group takes defaultChecked={defaultValue === option} on each radio, all sharing fieldProps (give each radio its own id after the spread):

import * as z from 'zod/mini';
import { BaseFieldSchema } from '@schema-engine/forms';
import { useFormField } from '@schema-engine/forms-react/hooks';

const CheckboxSchema = z.extend(BaseFieldSchema, { $type: z.literal('checkbox') });

const RadioSchema = z.extend(BaseFieldSchema, {
	$type: z.literal('radio'),
	options: z.array(z.object({ value: z.string() })),
});

export function CheckboxField(config: z.output<typeof CheckboxSchema>) {
	const { defaultValue, fieldProps } = useFormField(config);
	return <input type="checkbox" {...fieldProps} defaultChecked={Boolean(defaultValue)} />;
}

export function RadioField(config: z.output<typeof RadioSchema>) {
	const { defaultValue, fieldProps } = useFormField(config);
	return config.options.map(({ value }) => (
		<input
			key={value}
			type="radio"
			value={value}
			{...fieldProps}
			id={`${config.id}-${value}`}
			defaultChecked={defaultValue === value}
		/>
	));
}

A component that takes value and onChange

Pass { controlled: true } and hand the component what the hook returns. The field re-renders whenever its value changes:

import * as z from 'zod/mini';
import { BaseFieldSchema } from '@schema-engine/forms';
import { useFormField } from '@schema-engine/forms-react/hooks';

const DateSchema = z.extend(BaseFieldSchema, { $type: z.literal('date') });

interface DatePickerProps {
	value: Date | undefined;
	onChange(value: string): void;
	onBlur(): void;
}

function DatePicker({ value, onChange, onBlur }: DatePickerProps) {
	return (
		<input
			type="date"
			value={value?.toISOString().slice(0, 10) ?? ''}
			onChange={(event) => onChange(event.target.value)}
			onBlur={onBlur}
		/>
	);
}

function toDate(value: unknown): Date | undefined {
	return typeof value === 'string' && value !== '' ? new Date(value) : undefined;
}

export function DateField(config: z.output<typeof DateSchema>) {
	const { value, onChange, onBlur } = useFormField(config, { controlled: true });
	return <DatePicker value={toDate(value)} onChange={onChange} onBlur={onBlur} />;
}

Declare the value

Every registration of an input declares the value its control writes, with value: a function of the configured element that returns a Standard Schema. The rating above writes a whole number from one to its max, a text field a string. The engine composes these into the schema every submission is checked against and the type of onSubmit (see Submitted values), so the control writes exactly what it declares: a select with number options writes the number, not its text, and a checkbox writes a boolean. A control that writes something its declaration rejects fails the submission with a valueMismatch issue at its path. A static element, such as the submit button, uses defineStatic and declares none.

What the form does for an uncontrolled field

  • It reads the control. Text from .value, a checkbox from .checked (a checkbox with a value attribute adds or removes that value in an array), a radio group from the checked radio, a select multiple from its selected options, a number input from valueAsNumber and a file input from its files.
  • It writes changes back. A reset, setValue in code or a row update writes into the control through its ref, 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 holds 1e is left alone. File inputs are only cleared.
  • Rows keep their elements. On a row move the ref re-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 ref attaches, 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 ref lands 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

WidgetMode
input, textareaUncontrolled
field array shellBinds 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 zoneControlled

The other hooks

useFormField(path) reads the state of a path, useWatch(path) its value, useFieldArray(path) edits a list and useFormContext() reaches the form's commands and lazy formState. Hooks is the reference. A component re-renders only for the formState keys it reads, so a submit button that reads submission.status does not render while the user types.

Values are unknown, so a text control passes its default through fieldText(value), which gives the text a text control shows.