Sub topic 2
Registering inputs with register
This chapter assumes you know React function components and hooks, TypeScript generics, and how an HTML form fires its submit event. You should also have seen useForm in the previous chapter. Here you will learn what register returns, how to apply it to each kind of input, and which mistakes cause missing values.
What register does
register is a function returned by useForm. You call it with a field name, and it returns four props that connect one input to the form.
import { useForm } from "react-hook-form";
type Values = { email: string };
export function Demo() {
const { register } = useForm<Values>({ defaultValues: { email: "" } });
const props = register("email");
console.log(Object.keys(props)); // ["onChange", "onBlur", "name", "ref"]
return <input {...props} />;
}Each prop has a job:
| Prop | Purpose |
|---|---|
| `name` | The key under which the value is stored, such as `"email"`. |
| `ref` | Gives React Hook Form the DOM element, so it can read the value and focus the input on error. |
| `onChange` | Reports each change to the form's internal store. |
| `onBlur` | Reports that the user left the field, which marks it as touched. |
Writing {...register("email")} therefore connects the input in one step. The input stays uncontrolled. React does not hold its value in state, and the form reads it from the DOM element through ref. Typing in the field does not re-render your component.
Field names are typed paths
When you pass a type to useForm, the name argument is checked against it. Misspelling "emial" is a compile error. Nested objects and arrays use dot paths.
import { useForm } from "react-hook-form";
type Profile = {
name: string;
address: { city: string; zip: string };
tags: string[];
};
export function ProfileForm() {
const { register, handleSubmit } = useForm<Profile>({
defaultValues: {
name: "",
address: { city: "", zip: "" },
tags: ["", ""],
},
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
<input {...register("name")} />
<input {...register("address.city")} />
<input {...register("address.zip")} />
<input {...register("tags.0")} />
<input {...register("tags.1")} />
<button type="submit">Save</button>
</form>
);
}On submit, values is a real nested object: { name, address: { city, zip }, tags: [...] }. You do not need to build it yourself.
Different input types give different values
The value you receive depends on the element. These rules cause many "why is this false?" questions.
| Element | Value you get |
|---|---|
| Text, email, password, textarea | `string` |
| `<select>` | `string` (the selected option's value) |
| Radio group (same name) | `string` of the checked radio, or `null` if none |
| One checkbox with no `value` attribute | `boolean` |
| One checkbox with a `value` attribute | the `value` string when checked, otherwise `false` |
| Several checkboxes with the same name | `string[]` of the checked values |
| `<input type="file">` | `FileList` |
A group of checkboxes shows the array behavior:
import { useForm } from "react-hook-form";
type Prefs = { newsletter: boolean; topics: string[]; plan: string };
export function PrefsForm() {
const { register, handleSubmit } = useForm<Prefs>({
defaultValues: { newsletter: false, topics: [], plan: "free" },
});
return (
<form onSubmit={handleSubmit((v) => console.log(v))}>
<label>
<input type="checkbox" {...register("newsletter")} /> Newsletter
</label>
<label>
<input type="checkbox" value="react" {...register("topics")} /> React
</label>
<label>
<input type="checkbox" value="zod" {...register("topics")} /> Zod
</label>
<label>
<input type="radio" value="free" {...register("plan")} /> Free
</label>
<label>
<input type="radio" value="pro" {...register("plan")} /> Pro
</label>
<button type="submit">Save</button>
</form>
);
}Checking React and Zod gives topics: ["react", "zod"]. Checking nothing gives [] because the default value is an empty array.
Converting values with register options
register accepts a second argument with options. Three of them convert the value before it reaches your form state.
valueAsNumber: trueconverts the string to a number. An empty input becomesNaN, not0.valueAsDate: trueconverts the string to aDate. It works with date inputs.setValueAs: fnruns your function on the raw value. It is the escape hatch for anything else. Its result is also used when validation runs.
import { useForm } from "react-hook-form";
type Values = { age: number; nickname: string };
export function ConvertForm() {
const { register, handleSubmit } = useForm<Values>();
return (
<form onSubmit={handleSubmit((v) => console.log(v))}>
<input type="number" {...register("age", { valueAsNumber: true })} />
<input
{...register("nickname", { setValueAs: (v: string) => v.trim() })}
/>
<button type="submit">Send</button>
</form>
);
}This keeps the form value as a number, which matches a z.number() schema you will add in a later chapter. Without valueAsNumber, an <input type="number"> still produces a string.
The disabled: true option also deserves caution. A field registered as disabled submits undefined, as if it were absent. Setting the HTML disabled attribute on the input yourself does not change registration, so the value may then be missing in a way that surprises you.
Built-in rules versus a schema
register can also take validation rules such as required and minLength. This tutorial puts all rules in a Zod schema instead. When you pass a resolver to useForm, the resolver validates the whole form and the built-in rules are not used. Keep register("email") free of rules and put the rules in the schema, so there is one place to read them.
Common errors
- Forgetting the spread.
register("email")alone does nothing. You must write{...register("email")}on the element. - Adding your own
valueandonChange. Puttingvalue={x}oronChange={...}after the spread overrides the registered props. The form then stops seeing changes. UsedefaultValuesfor initial values. - Registering a custom component that drops
ref.registerneeds the DOM element. If yourInputcomponent wraps<input>, it must passrefthrough. With React 19,refis a normal prop. Before React 19, wrap the component inforwardRef. If you cannot expose the element, useController, covered in a later chapter. - Missing
defaultValues. Without them, a field starts asundefined, not"". Changing between uncontrolled and controlled can then produce warnings, and a schema expecting a string may report a type error instead of your message. - Duplicate names with different meanings. Two text inputs with the same name share one value slot. Only checkbox and radio groups are meant to share a name.
- Reusing a name as a key. Changing the name string between renders re-registers the input under a new key. Keep names stable.
Check your understanding
Exercise
A teammate wrote <input {...register("email")} value={email} onChange={(e) => setEmail(e.target.value)} /> and reports that handleSubmit receives an empty email. Explain what went wrong and give the fix.
Show answer
The value and onChange props written after the spread replace the onChange returned by register, so the form never receives the typed text. The input also becomes controlled by React state instead of by the form. The fix is to remove value and onChange and the extra state, use defaultValues: { email: "" } in useForm, and keep only {...register("email")} on the input. If you need the current value elsewhere, read it with watch, which a later chapter covers.
Exercise
You have <input type="checkbox" value="zod" {...register("topics")} /> and <input type="checkbox" value="react" {...register("topics")} /> with defaultValues: { topics: [] }. What does topics contain after the user checks only "react"? What would it contain if the form had a single checkbox with no value attribute registered as "agree"?
Show answer
With the two same-name checkboxes, topics is ["react"], an array of checked values. A single checkbox with no value attribute registered as "agree" yields a boolean: true when checked and false when not.