CodeBlanks Logo Icon CodeBlanks

Summary - react-hook-form

Write a validated registration form with name and email fields.

Summary - react-hook-form

In this group you learned what react-hook-form is, how to use register and handleSubmit, and how to validate with a Zod model. Now it's time to combine them.

Typical flow: call useForm, bind fields with register, submit with handleSubmit, show errors with formState.errors. Make validation central with a Zod model.

In the next step you will write a validated registration form with name and email fields.

Practice Write a registration form

Complete the skeleton. Write a RegistrationForm component. Define const formModel = z.object({ name: z.string().min(2), email: z.string().email() });. Call useForm({ resolver: zodResolver(formModel) }); get register, handleSubmit and formState: { errors }. Inside <form onSubmit={handleSubmit(onSubmit)}> put two inputs (name and email) and {errors.name &&

Name required

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

Starter code

App.jsx
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';

// Write RegistrationForm here

Sample solution

App.jsx
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';

const formModel = z.object({
  name: z.string().min(2),
  email: z.string().email(),
});

function RegistrationForm() {
  const { register, handleSubmit, formState: { errors } } = useForm({ resolver: zodResolver(formModel) });
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('name')} />
      {errors.name && <p>Name required</p>}
      <input {...register('email')} />
      <button type="submit">Sign up</button>
    </form>
  );
}

export default RegistrationForm;

Questions and answers

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

1 Which topic was NOT covered?

  • register
  • handleSubmit
  • zodResolver
  • useTransition Correct answer

Explanation: useTransition was not covered.

2 handleSubmit usage

Question
<form onSubmit={____(onSubmit)}>
Answer
<form onSubmit={handleSubmit(onSubmit)}>

Explanation: handleSubmit wraps submission.

All lessons in Advanced