CodeBlanks Logo Icon CodeBlanks

register and handleSubmit

Learn to bind fields with register.

register details

The register function takes a field name and optional validation options. register('name', { required: true }) makes the field required.

Errors are kept in formState.errors. You can show an error message with {errors.name &&

Name required

}.

react-hook-form does not keep separate state per field; this is why it stays fast even with thousands of fields.

formState.errors

The formState.errors object holds the error for each field. You check the error type with errors.name?.type === 'required'.

You can give an optional message with register('name', { required: 'Name required' }); it is read via errors.name?.message.

This structure cuts code repetition and centralises error handling.

Practice Write a form with validation

Complete the skeleton. Write a SignupForm component. Call useForm; get register, handleSubmit and formState: { errors }. Inside <form onSubmit={handleSubmit(onSubmit)}> put <input {...register('email', { required: true })} /> and {errors.email &&

Email required

}. Add <button type="submit">Submit</button>. onSubmit = (data) => console.log(data). Add export default.

Starter code

App.jsx
import { useForm } from 'react-hook-form';

// Write SignupForm here

Sample solution

App.jsx
import { useForm } from 'react-hook-form';

function SignupForm() {
  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('email', { required: true })} />
      {errors.email && <p>Email required</p>}
      <button type="submit">Submit</button>
    </form>
  );
}

export default SignupForm;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Where is a validation error kept?

  • In window
  • In localStorage
  • In useState
  • In formState.errors Correct answer

Explanation: Errors are in formState.errors.

2 required option

Question
register('name', { ____: true });
Answer
register('name', { required: true });

Explanation: required makes the field required.

3 register and handleSubmit: match the terms

Term Meaning
errors Error object
register Binds field
required Required
message Error text

All lessons in Advanced