Forms

Build validated, reactive forms with minimal boilerplate.

Controlled and uncontrolled fields

A field's props follow React 19's rules, on every path: h(), compiled JSX, a spread, a server render and hydration.

  • value (a text input, a <textarea>, a <select>) and checked (a checkbox or radio) control what the field shows. A signal or a function keeps it live. In compiled JSX, a field whose value or checked reads state shows that state: after each edit, once the handlers have run, a field whose state did not take the edit is put back, as React does. A constant, a value a spread read once ({...form.register('title')}) and a field made with h() keep the user's edit until the binding writes a different value.
  • defaultValue, defaultChecked, an <option>'s selected or defaultSelected, and a <select>'s defaultValue (the options it names; an array for multiple) are the field's default: what it shows while nothing controls it, and what a form reset restores.
  • A value or checked of null or undefined releases the field. A field it controlled shows nothing (an empty value, unchecked, no option selected), and the next reset restores its default. A field it never controlled keeps its default.
  • A select's value selects options by their value (the value attribute, else the text with HTML whitespace collapsed): a string selects the first option with it, in a multiple select too, and an array every option it names. It does so whenever its options change, so options a <For> or <Show> adds after a fetch show the value too.
  • After <Form>'s action succeeds, the form is reset: uncontrolled fields go back to their defaults, and a controlled one shows what its prop holds.
  • A server writes what the field shows first, its value, else its default, in the one place the markup has for it (an input's value and checked attributes, a textarea's text, the options' selected), so a form posted before any script runs submits it. Hydration then writes the declared defaults back.
  • A field the user changed before hydration ran keeps what they left in it, controlled or not, and no input or change event is dispatched for it: handlers see the edits made after hydration. Released React (react-dom 19.3) keeps an edited input, checkbox, radio or select the same way, but puts a <textarea> back to the server's text as it hydrates, controlled or not; What keeps the textarea's draft too. A value the browser restores on a back or forward navigation looks exactly like an edit, so a replayed event would run a handler nobody triggered. A field counts as changed when it differs from what the same markup shows untouched, as the browser's own reset computes it (a range at its midpoint, a color at #000000, a select whose first options are disabled), so an untouched field is left as it is. A file chosen before hydration stays in the form and submits with it (a form with a file input takes enctype="multipart/form-data"; see A form with a file). A controlled field's prop still counts as written: the binding's next write of another value replaces the user's change.

A field the user changed before hydration

Hydration keeps such a field as the user left it and dispatches no event for it, so a signal that holds its value still holds the server's. onMount and useEffect run once every field shows what the user left in it: to react to the change, read the field in onMount and write your state from it. A country picked while the page loaded then decides the regions offered:

import { signal, onMount } from 'what-framework';

const REGIONS = { CA: ['BC', 'ON'], US: ['NY', 'TX'] };

export function Address() {
  const country = signal('CA');
  let select;
  onMount(() => country(select.value));
  return (
    <fieldset>
      <select name="country" ref={(el) => { select = el; }} value={country()} onChange={(e) => country(e.currentTarget.value)}>
        <option value="CA">Canada</option>
        <option value="US">United States</option>
      </select>
      <select name="region">
        {REGIONS[country()].map((region) => <option key={region} value={region}>{region}</option>)}
      </select>
    </fieldset>
  );
}

A query keyed on country() (query(() => ['regions', country()], fetchRegions)) fetches the new country's regions the same way. Reading the field later (a microtask, a timer) is not needed: in onMount it already shows the user's choice.

Server validation, with and without JavaScript

The dispatch of useActionState(serverAction, initial) as a <Form>'s action gives one edit form that works in both modes. The action is called as savePost(previousState, fields) and returns the error, with the fields as typed, as a value; the fields' defaults come from the state. A save redirects to the post:

import { getResponse, useActionState } from 'what-framework';
import { Form, action } from 'what-framework/server';

export const savePost = action(async (previous, fields) => {
  const typed = String(fields.title ?? '');
  const title = typed.trim();
  if (title.length < 3) return { error: 'Title needs three characters', fields: { title: typed } };
  await db.posts.update(fields.slug, { title });
  getResponse().redirect(`/posts/${fields.slug}`);
  return { saved: true };
}, { id: 'savePost' });

function EditPost({ post }) {
  const [state, save] = useActionState(savePost, null);
  return (
    <Form action={save}>
      <input type="hidden" name="slug" value={post.slug} />
      <input name="title" defaultValue={() => state()?.fields?.title ?? post.title} />
      {() => state()?.error && <p role="alert">{state().error}</p>}
      <button type="submit">Save</button>
    </Form>
  );
}
  • With JavaScript the result becomes state, then the form resets to the defaults that state gives: the typed title stays next to the error. A redirect from the action is followed once what it revalidates has landed, through the mounted <Router>.
  • Without JavaScript the form posts to the page it is on, with the state it holds and its hook's key. createRequestHandler runs the action by the action endpoint's rules (CSRF checks, the body limit, registered actions only) and renders the page with the result for that form alone: another form of the same action keeps its own state. Inside a keyed list (a <For key> row, a .map() row with a key) the key follows the row's key, as React's key path does, so a record's editor gets its own result back even when records were added, removed or reordered between the page and the post. A list's or a component's place is where it is written, so a list or a component before it that is there in one render and not in the other (a Pinned table the record joins, a section shown while it has rows) moves no other list's rows. A helper function called twice in a component renders the same JSX twice, told apart by order: write it as a component when one of its calls is conditional. Forms that repeat without a key are told apart by position only: a change in their order in between hands the result to the form now in that place. A row key is a string or a finite number. The page carries it as a digest under the render's salt, which hides a long random key but not one that can be guessed (the salt is in the page, so a guess is checked in a moment): keep secrets, such as an email address or a small private id, out of row keys. The render is the visitor's own, outside the ISR cache. There is no size limit but the body's: bodyLimit on createRequestHandler, 1 MB by default, and a post over it gets a 413 page. The state carries the fields as typed, so a re-post holds the draft twice and a draft fits in about half the limit. No cookie or Referer is involved. A redirect from the action answers 303. Reloading the page, or going back to it, posts the form again, as with any form POST; a redirect on success avoids that.
  • The state is the visitor's own data, which they can post as anything: show it, and trust it for nothing else.
  • <Form action={serverAction} redirect="/x"> stays fire and redirect: without JavaScript what the action returns is not carried back. Without redirect it comes back to the page it is on.
  • A custom server runs page-posted forms with createFormPostHandler(options) and renders with its actionState; nodeActionMiddleware serves only the action endpoint.

A form with a file

Give the form enctype="multipart/form-data", as HTML requires, and the action gets the file as a Web File in its fields, with JavaScript and without: a multipart post is read by the platform's own parser into the same fields an urlencoded one gives, and with JavaScript the dispatch sends the form's fields as that same form. A file input with nothing chosen is an empty File (size 0, name ''), as the platform's parser gives it: test size === 0, not the empty string. The whole body is within bodyLimit (1 MB by default). A body over it runs nothing: without JavaScript the visitor gets the 413 page naming the limit, and with JavaScript the call rejects with ERR_PAYLOAD_TOO_LARGE (status 413, limit the bytes allowed), which reaches the nearest <ErrorBoundary> above the component that dispatched it, as any error an action throws: a page with none shows nothing. Check the file's size on its input before the form is sent, which keeps what the visitor typed, and put the form's component in a boundary that names error.limit, as below. A proxy's or platform's own 413 carries no limit: its error.message says the server accepts less in one request.

export const signup = action(async (previous, fields) => {
  const avatar = fields.avatar; // a File; an empty one (size 0) when none was chosen
  if (!(avatar instanceof File) || avatar.size === 0) {
    return { error: 'Attach an avatar', fields: { email: fields.email } };
  }
  await saveAvatar(fields.email, await avatar.arrayBuffer());
  getResponse().redirect('/welcome');
  return { saved: true };
}, { id: 'signup' });

const MAX_UPLOAD = 1_000_000; // bodyLimit, less room for the other fields

function Signup() {
  const [state, save] = useActionState(signup, null);
  return <Form action={save} enctype="multipart/form-data">
    <input name="email" defaultValue={() => state()?.fields?.email ?? ''} />
    <input type="file" name="avatar" accept="image/*" onChange={(e) => {
      const file = e.target.files[0];
      e.target.setCustomValidity(file && file.size > MAX_UPLOAD ? 'Choose a file under 1 MB' : '');
    }} />
    <button type="submit">Create account</button>
  </Form>;
}

// Around the component whose useActionState dispatched the action.
<ErrorBoundary fallback={({ error, reset }) => (
  <p role="alert">
    {error.code === 'ERR_PAYLOAD_TOO_LARGE' && error.limit !== undefined ? `Too large: the limit is ${error.limit} bytes.` : error.message}
    <button onClick={reset}>Try again</button>
  </p>
)}>
  <Signup />
</ErrorBoundary>
  • The whole body, every field and file in it, is within bodyLimit (1 MB by default): raise it for uploads, createRequestHandler({ routes, bodyLimit: 8 * 1024 * 1024 }). A post over it gets a 413 page.
  • What the action returns never carries a file back: a File in it is null in the state, with and without JavaScript. Return the text fields the form shows again, and what the page shows about the file (its name, its size) as a value of its own.
  • A file input cannot be filled in again after a validation error (a browser rule): the visitor chooses the file again, so say so next to the error.
  • Without the multipart enctype a form posts a file's name alone, with JavaScript too, as the browser's own submit of it does.

useForm

useForm provides complete form state management, field registration, validation, and submission handling in a single hook. It uses per-field signals internally so that updating one input never causes unrelated fields to re-render.

import { useForm } from 'what-framework/form';

const { register, handleSubmit, formState } = useForm({
  defaultValues: { email: '', password: '' },
  mode: 'onSubmit',        // 'onSubmit' | 'onChange' | 'onBlur'
  reValidateMode: 'onChange',
  resolver: undefined,     // no resolver means no validation at all
  shouldUnregister: false, // true: a field leaves the values when its component goes
});

All validation lives in resolver. Without one, validate() resolves true immediately and handleSubmit always takes the valid branch, which leaves mode and reValidateMode with nothing to do. Per-field rules in the second argument to register (the React Hook Form shape, register('email', { required: true })) are not supported: register reads only type, value, ref and shouldUnregister from its options and ignores the rest.

Return Value

useForm returns an object with the following properties:

Property Description
register(name, opts?)Connect a field to the form. The name is a path (Names are paths)
unregister(name?, opts?)Forget fields, or every field (unregister)
handleSubmit(onValid, onInvalid?)Returns a submit handler that validates first
setValue(name, value, opts?)Set a field value in form state
getValue(name)Read a field's current value
setError(name, error)Manually set a field error
clearError(name)Clear a single field's error
clearErrors()Clear all errors at once
reset(newValues?)Reset form state to the defaults, or to new values, which become the defaults (dirtyFields is measured from them and a later reset() returns to them), as in React Hook Form
watch(name?)Returns a computed signal for one field or all values
validate(name?)Trigger validation for one field or the entire form
controlWhat useFieldArray takes
formStateReactive state object (see below)

formState

The formState object exposes reactive getters and methods:

Property Type Description
valuesobjectAll current field values, nested by the fields' paths
errorsobjectAll current errors keyed by field name ('vehicles.0.vin')
error(name)object | nullThe { type, message } error for one field, or null
touchedobjectFields the user has interacted with
isDirty()booleanWhether any field has been modified
isValid()computedTrue when there are zero errors
isValidating()booleanTrue while async validation is running
isSubmitting()booleanTrue during async submit
isSubmitted()booleanTrue after first submit attempt
submitCount()numberHow many times the form was submitted
dirtyFields()computedObject mapping dirty field names to true

Complete Example

A registration form with email, password, and password confirmation:

import { useForm, simpleResolver, rules } from 'what-framework/form';

const { register, handleSubmit, formState } = useForm({
  defaultValues: { email: '', password: '', confirmPassword: '' },
  mode: 'onBlur',
  resolver: simpleResolver({
    email:           [rules.required(), rules.email()],
    password:        [rules.required(), rules.minLength(8)],
    confirmPassword: [rules.required(), rules.match('password', 'Passwords must match')],
  }),
});

function Register() {
  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <input {...register('email')} type="email" placeholder="Email" />
      <input {...register('password')} type="password" placeholder="Password" />
      <input {...register('confirmPassword')} type="password" placeholder="Confirm" />
      <button type="submit">Sign Up</button>
    </form>
  );
}

register()

The register function connects a form field to the reactive state. Call it with a field name and spread the returned props onto your input element.

const emailProps = register('email');
// Returns: { name, value, onchange, onBlur, onFocus, ref }
// The event key is lowercase 'onchange': React's change event, which a text field fires on each key.

// register(name, { type: 'checkbox' }) swaps value for checked:
//   { name, checked, onchange, onBlur, onFocus, ref }

// register(name, { type: 'radio', value }) returns:
//   { name, value, checked, onchange, onBlur, onFocus, ref }

// Spread onto any input element
<>
  <input {...register('email')} type="email" />
  <textarea {...register('bio')} />
  <select {...register('role')}>
    <option value="admin">Admin</option>
    <option value="user">User</option>
  </select>
</>

Each registered field gets its own internal signal. This means typing into the email field only updates components that read the email value, not every field in the form.

In compiled JSX a spread follows the field: its value (or checked) is a getter that the spread's binding reads again, so setValue and reset show in the input. An h() call reads it once (a JavaScript spread copies the value): the input takes the user's edits, but a later setValue or reset does not show. There, bind the value as a thunk:

<input
  name="email"
  value={() => getValue('email')}
  onChange={register('email').onchange}
/>

A registered radio's checked is a thunk, so a radio follows setValue and reset on every path. A registered file input's field holds its FileList (values.photo[0] is the File), as in React Hook Form, and nothing is written to the input.

Checkbox and radio handling

register automatically detects type="checkbox" inputs and reads e.target.checked instead of e.target.value, so boolean fields work out of the box. Radios work differently, because every radio in a group shares one field that holds the selected option's value. Tell the registration which value this radio contributes, register('plan', { type: 'radio', value: 'pro' }), or let Radio do it for you. A bare register('plan') spread onto an <input type="radio"> reports ERR_FORM_RADIO_UNTYPED at mount in development, because the registration's own value binding overwrites the input's value and the group is then unable to record a choice.

Validation

What provides a set of built-in validation rules through the rules export. Combine them with simpleResolver to define constraints per field.

Built-in Rules

Rule Signature Description
requiredrequired(message?)Fails on empty, null, or undefined
minLengthminLength(n, message?)String must be at least n characters
maxLengthmaxLength(n, message?)String must be at most n characters
minmin(n, message?)Number must be at least n. A numeric string is compared as the number it spells; a blank one is skipped
maxmax(n, message?)Number must be at most n. A numeric string is compared as the number it spells; a blank one is skipped
patternpattern(regex, message?)String must match the regex
emailemail(message?)Must be a valid email address. Also fails on ''
urlurl(message?)Must be a valid URL. Skips an empty value
matchmatch(field, message?)Must equal the value of another field
customcustom(fn)Pass any (value, allValues) => string | undefined

Every rule is a plain function of the value, and every rule except required and match skips a value of the wrong type. Two consequences are worth spelling out. register stores e.target.value, which is a string even for <input type="number">; min and max compare a numeric string as the number it spells and leave a blank or non-numeric one to required and pattern. And email tests any string including the empty one, so an untouched optional email field stays invalid and blocks submission (url skips empty, email does not).

Example with Multiple Rules

import { simpleResolver, rules } from 'what-framework/form';

const resolver = simpleResolver({
  username: [
    rules.required('Username is required'),
    rules.minLength(3, 'At least 3 characters'),
    rules.maxLength(20),
    rules.pattern(/^[a-zA-Z0-9_]+$/, 'Letters, numbers, and underscores only'),
  ],
  // A typed value is a string, so range-check it with custom()
  age: [
    rules.required(),
    rules.custom((v) => (Number(v) >= 13 && Number(v) <= 120
      ? undefined
      : 'Must be between 13 and 120')),
  ],
  website: [
    rules.url('Enter a valid URL'),
  ],
});

Displaying Errors

Errors appear after the component has already run, and a component body runs exactly once. So the error has to be read inside a reactive thunk, {() => ...}: the thunk is the part that re-runs. Read formState.errors there and render the message yourself, or drop in ErrorMessage, which does exactly that for you.

import { ErrorMessage } from 'what-framework/form';

<form onSubmit={handleSubmit(onValid)}>
  <input {...register('email')} type="email" />

  {/* the thunk reads the error, so it re-runs when it changes */}
  {() => formState.errors.email &&
    <span class="field-error">{formState.errors.email.message}</span>}

  {/* or let ErrorMessage keep it current */}
  <ErrorMessage name="email" formState={formState} />
</form>

ErrorMessage renders <span class="what-error" role="alert"> with the message, or calls a render={({ message, type }) => ...} prop when you want the markup to be yours. It renders a reactive thunk of its own, so the message appears when the field gets an error, changes with it, and goes away when the field is valid again.

Schema Validation

For complex forms, use zodResolver or yupResolver to validate against a schema. This keeps validation logic declarative and co-located with your type definitions.

Resolvers fail closed

zodResolver works on both Zod 3 and Zod 4. It reads ZodError.issues and falls back to the errors alias that only Zod 3 carries. If a schema throws something that is not a validation error, at all, both zodResolver and yupResolver rethrow rather than reporting the form as valid, so a broken schema is loud instead of silently disabling validation.

Zod Example

import { z } from 'zod';  // zod 3 or 4
import { useForm, zodResolver } from 'what-framework/form';

const schema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'At least 8 characters'),
  age: z.number().min(13).max(120),
});

const { register, handleSubmit } = useForm({
  resolver: zodResolver(schema),
  defaultValues: { email: '', password: '', age: 0 },
});

Yup Example

import * as yup from 'yup';
import { useForm, yupResolver } from 'what-framework/form';

const schema = yup.object({
  email: yup.string().email().required(),
  password: yup.string().min(8).required(),
});

const { register, handleSubmit } = useForm({
  resolver: yupResolver(schema),
});

Custom resolvers

A resolver is any async function that accepts values and returns { values, errors }. Use simpleResolver(rules) for lightweight validation without pulling in Zod or Yup.

Field arrays

Forms that hold a list (vehicles, drivers, line items) name each item's fields by its place and keep the items with useFieldArray, as in React Hook Form.

Names are paths

A field's name is a path: register('vehicles.0.vin') reads and writes values.vehicles[0].vin, and register('address.city') values.address.city. formState.values, watch(), what handleSubmit hands over and what a resolver is given are nested, so a schema describes the form's arrays and objects as they are. A field starts from the default at its path. formState.errors, formState.error(name), touched and dirtyFields stay keyed by the field's name (errors['vehicles.0.vin']), which is how zodResolver and yupResolver name a nested issue. A name without a dot is a key, as it always was.

import { z } from 'zod';
import { useForm, zodResolver } from 'what-framework/form';

const schema = z.object({
  vehicles: z.array(z.object({ vin: z.string().length(17, 'A VIN has 17 characters') })).min(1),
});

const { register, formState } = useForm({
  resolver: zodResolver(schema),
  defaultValues: { vehicles: [{ vin: '' }] },
});
register('vehicles.0.vin');
formState.error('vehicles.0.vin'); // the issue at path ['vehicles', 0, 'vin']

Forgetting a field: unregister

unregister(name | names, options?) forgets fields, or every field when called with no name: the value leaves formState.values and what handleSubmit hands over, along with its default; its error leaves formState.errors, so isValid follows; its touched state goes; and a validation of it still in flight never lands. { keepValue, keepError, keepTouched, keepDefaultValue } keep what they name. An input that still shows the field shows its default, and the next edit in it brings the field back. register(name, { shouldUnregister: true }), or useForm({ shouldUnregister: true }) for every field, unregisters a field when the component that registered it goes: a field inside <Show> leaves the values when it is hidden. It keeps the field's default, as keepDefaultValue does, so the field shown again starts from it.

useFieldArray

useFieldArray({ control: form.control, name }) (or { form, name }) keeps the items of an array field. fields() lists them, each with an id to key its row by. append, prepend and insert take an item or an array of items; remove(index | indexes) removes those items, or every item with no argument; move(from, to) and swap(a, b) reorder; update(index, item) makes the item at index a new one (its row is built again) and replace(items) replaces them all, as setValue(name, items) does. An item's values, errors and touched state belong to the item, not its index: they move with it, and a removed item's go with it. reset() takes the items from the defaults again.

import { useForm, useFieldArray } from 'what-framework/form';

function DriverRow({ field, index, form, drivers }) {
  // Built once: `index` is the row's place when it was built.
  const place = () => drivers.fields().findIndex((f) => f.id === field.id);
  return (
    <li>
      <label>{() => `Driver ${place() + 1}`} <input {...form.register(`drivers.${index}.name`)} /></label>
      <button type="button" onClick={() => place() > 0 && drivers.move(place(), place() - 1)}>Up</button>
      <button type="button" onClick={() => drivers.remove(place())}>Remove</button>
      <span role="alert">{() => form.formState.error(`drivers.${place()}.name`)?.message ?? ''}</span>
    </li>
  );
}

export function Drivers() {
  const form = useForm({
    defaultValues: { drivers: [{ name: 'Ada' }, { name: 'Grace' }] },
    resolver: async (values) => {
      const errors = {};
      values.drivers.forEach((driver, i) => {
        if (!driver.name.trim()) errors[`drivers.${i}.name`] = { type: 'required', message: 'Enter a name' };
      });
      return { values, errors };
    },
  });
  const drivers = useFieldArray({ control: form.control, name: 'drivers' });
  return (
    <form onSubmit={form.handleSubmit((values) => console.log(values.drivers))}>
      <ul>
        {drivers.fields().map((field, index) => <DriverRow key={field.id} field={field} index={index} form={form} drivers={drivers} />)}
      </ul>
      <button type="button" onClick={() => drivers.append({ name: '' })}>Add a driver</button>
      <button type="submit">Save</button>
    </form>
  );
}

A row is built once

The index a row is built with is its place at that moment. register, watch(name) and a nested useFieldArray take the name when they are called and keep that item while rows move around it; an input's name attribute follows the item's place. Anything read again later, such as the row's label or its error, reads the place now: fields().findIndex((f) => f.id === field.id). A row built after its parent moved (an incident added to a driver who was moved) names the parent by its place now, too.

move and swap keep each row's elements, so the field being typed in keeps its focus and caret where the browser has Element.moveBefore (Chromium, Firefox). React Hook Form's append focuses the new item's first field; What's does not, so focus it yourself if you want that.

useField

useField gives you standalone control over a single field without a parent useForm. This is useful for isolated inputs like search bars, inline edits, or fields managed outside a form context.

import { useField } from 'what-framework/form';

const username = useField('username', {
  defaultValue: '',
  validate: (v) => v.length < 3 ? 'Too short' : undefined,
});

Return Value

Property Description
nameThe field name string
value()Current value (reactive)
error()Current error message or null
isTouched()Whether the field has been blurred
isDirty()Whether the field has been written to since the last reset()
setValue(v)Set the value programmatically
setError(e)Set the error message manually
validate()Run the validate function manually
reset()Reset to default value and clear state
inputProps()Returns { name, value, onInput, onBlur } to spread
function SearchBar() {
  const search = useField('search');

  return (
    <div>
      <input {...search.inputProps()} placeholder="Search..." />
      {() => search.error() &&
        <span class="error">{search.error()}</span>
      }
    </div>
  );
}

useField vs register

Use register when you already have a useForm instance and want coordinated validation and submission. Use useField when a field is independent or you need fine-grained control over its lifecycle.

Form Components

What exports a few small components that call register for you and spread the result. Each accepts a register prop (the register function from useForm) plus any standard HTML attributes.

Component Renders Notes
Input<input>Sets aria-invalid when you pass an error prop
Textarea<textarea>Sets aria-invalid when you pass an error prop
Select<select>Pass <option> elements as children
Checkbox<input type="checkbox">Takes its initial checked from the registered value; toggling writes back
Radio<input type="radio">Needs its own value. Writes that value to the shared field and keeps checked in sync in both directions
ErrorMessage<span role="alert">Shows error text or uses a custom render prop. Reactive on its own: it renders nothing until the field has an error (see Displaying Errors)

None of the input components consults formState. ErrorMessage is the exception: it reads formState.error(name), so it needs formState passed to it or it renders nothing. aria-invalid comes from an error prop you pass yourself, read once when the element is created. Pass the error value rather than a thunk: a function is always truthy, so it marks the field invalid from first paint.

Input, Textarea, Select, and Checkbox merge register() into your props: the field follows setValue and reset, and your onChange, onBlur, and onFocus run after the registration's. A ref handed to them is replaced by the registration's; Radio composes your ref with it too.

Reach for Radio when you need a radio group. Every radio in the group shares one field, and that field holds the selected option's value, so each one declares the value it contributes:

import { Radio } from 'what-framework/form';

<fieldset>
  <legend>Plan</legend>
  <label><Radio name="plan" value="free" register={register} /> Free</label>
  <label><Radio name="plan" value="pro" register={register} /> Pro</label>
  <label><Radio name="plan" value="team" register={register} /> Team</label>
</fieldset>

Picking one writes its value into plan, and the binding runs the other way too, so setValue('plan', 'pro'), reset(), and a defaultValues entry all move the selection on screen.

To wire a radio by hand, register it with its own value and keep type="radio" on the element. The type option tells the registration how to behave and does not set the element's type, so an input without the attribute is a text box that no click will ever change:

<fieldset>
  <input type="radio" {...register('plan', { type: 'radio', value: 'free' })} />
  <input type="radio" {...register('plan', { type: 'radio', value: 'pro' })} />
</fieldset>

A client-only alternative leaves the value option off and lets each input carry its own, the way a plain HTML radio group already works:

<fieldset>
  <input type="radio" value="sm" {...register('size', { type: 'radio' })} />
  <input type="radio" value="lg" {...register('size', { type: 'radio' })} />
</fieldset>

Those two forms behave identically in the browser: mount, setValue, reset, and a real click move the selection the same way either way. They are not the same on the server. A declared value gives the registration something to compare the field against, so the selected radio ships already checked, <input type="radio" name="plan" value="pro" checked>. Without one the registration has no value until an element hands it one through the ref, and the server renderer skips ref entirely, so every radio in the group serializes unchecked: a server-rendered page paints an empty radio group and only fills it in at hydration. Declare the value on anything you render on the server.

A radio that cannot say which value it stands for is treated as a mistake rather than given a default, since the DOM reports "on" for all of them and a group of those cannot record a choice. A Radio with no value reports ERR_FORM_RADIO_WITHOUT_VALUE in development and renders an unregistered input, so it never touches form state. A register(name, { type: 'radio' }) on an input carrying no value attribute reports the same code when it changes and leaves the field alone.

Building a Form with Components

import {
  useForm, Input, Textarea, Select, Checkbox, ErrorMessage,
  simpleResolver, rules,
} from 'what-framework/form';

function ContactForm() {
  const { register, handleSubmit, formState } = useForm({
    defaultValues: { name: '', message: '', topic: 'general', subscribe: false },
    resolver: simpleResolver({
      name:    [rules.required()],
      message: [rules.required(), rules.minLength(10)],
    }),
  });

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <Input name="name" register={register} placeholder="Your name" />
      <ErrorMessage name="name" formState={formState} />

      <Select name="topic" register={register}>
        <option value="general">General</option>
        <option value="support">Support</option>
        <option value="feedback">Feedback</option>
      </Select>

      <Textarea name="message" register={register} rows={4} />
      <ErrorMessage name="message" formState={formState} />

      <label>
        <Checkbox name="subscribe" register={register} />
        Subscribe to updates
      </label>

      <button type="submit">Send</button>
    </form>
  );
}

Always pass register as a prop

The pre-built components call register(props.name) internally. Make sure you pass the register function from your useForm instance, not the result of calling it.

Live Demo: Form Validation