React Hook Form with Zod

React Hook Form is a popular library for building forms in React. It provides a simple and efficient way to handle form state and validation. Zod, on the other hand, is a TypeScript-first schema validation library. Combining these two libraries can provide a seamless experience for validating form data.

In this blog post, we will explore how to use React Hook Form with Zod to validate form data.

Getting Started

Before we dive into the details, we need to make sure that we have both React Hook Form, Zod and React Hook Form Resolvers installed in our project.

npm install react-hook-form zod @hookform/resolvers

Once we have the dependencies installed, we can start using React Hook Form with Zod.

Using React Hook Form with Zod The first step is to define our form schema using Zod. This schema will define the structure and validation rules for our form data. For example, let's say we have a login form with two fields: email and password. We can define our schema as follows:

import * as z from 'zod'

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
})

Next, we can use the useForm hook from React Hook Form to create a form instance. We can pass in our form schema as an option to the useForm hook:

import { useForm } from 'react-hook-form'

const LoginForm = () => {
  const { register, handleSubmit } = useForm({
    resolver: zodResolver(loginSchema),
  })

  const onSubmit = (data) => {
    console.log(data)
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('email')} type="email" />
      <input {...register('password')} type="password" />
      <button type="submit">Submit</button>
    </form>
  )
}

Notice how we are passing in our schema to the zodResolver function. This function creates a resolver that will handle our schema validation. We can then pass this resolver as an option to useForm.

Finally, we can use the register function from React Hook Form to register our form inputs. This function returns an object with a ref and a name property that we can spread onto our input element. The ref property is used to reference the input element, and the name property is used to associate the input with a key in our form data object.

When the form is submitted, React Hook Form will validate the form data using our schema. If the data is valid, the onSubmit function will be called with the form data object.

Conclusion React Hook Form and Zod are two powerful libraries that can work together to create a seamless form validation experience. By defining our form schema using Zod and using it with React Hook Form, we can handle form validation and state management in a simple and efficient way.

I hope this blog post has been helpful. Happy coding!