Skip to content
satin

Forms with React Hook Form

A sign-up form validated with Zod through React Hook Form, its errors shown by Satin's Form.

React Hook Form keeps the values and runs the checks; Zod describes them once, with the messages. Satin's Form only shows the result: it takes the messages by field name, marks each control invalid and moves focus to the first one. Submit the empty form to see it, then try an address at example.com for an error that comes back from the server.

Any address at example.com is already taken here.

Terms

Install

Zod 4 and React Hook Form 7; @hookform/resolvers connects the two.

Terminal
npm i react-hook-form zod @hookform/resolvers

Inputs register, Radix controls use Controller

Input passes name, onChange, onBlur and ref to its <input>, so {...register('email')} goes straight on it. The field stays uncontrolled and typing doesn't re-render the form.

Select and Checkbox are Radix buttons, not native inputs, so React Hook Form can't read them from the DOM. Wrap them in a Controller and pass its value and onChange; its ref reaches the button, so setFocus works too. Checkbox reports 'indeterminate' as well as true and false, hence checked === true.

Errors by name

Form's errors is a plain record of messages, { email: 'Enter an email' }. React Hook Form keeps an object per field, so messages() turns one into the other. Each FormField and FieldGroup with a matching name shows its message in place of the description and wires it to the control with aria-describedby and aria-invalid. The helper covers flat forms; for nested values, name the fields by their path (address.city) and flatten the errors the same way.

A Checkbox doesn't read the group around it, so pass aria-invalid from fieldState yourself. That is also what lets Form find it and move focus to it.

Focus and server errors

Satin's Form moves focus to the first invalid control after a submit, in the order they appear on the page, and again whenever errors appear where there were none. React Hook Form would do the same on its own, so shouldFocusError: false leaves it to one of them. Errors that clear as people type never move focus.

An error from your API is one more message: setError puts it under the field, and Form takes focus there as it would after a failed check. While saving, show loading on the submit button rather than disabling the whole Form: a disabled field can't take the focus when the answer comes back. A loading button ignores clicks, so the form isn't sent twice.

SignUpForm.tsx
async function onValid(values: SignUp) {
  const res = await fetch('/api/sign-up', { method: 'POST', body: JSON.stringify(values) })
  if (res.status === 409) setError('email', { message: 'This email already has an account.' })
}