DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on

How to use Zod in React?

Zod is a TypeScript-first schema declaration and validation library. It's designed to work seamlessly with TypeScript and offers a concise way to define and validate data structures. To use Zod in a React application, you can follow these steps:

  1. Install Zod: Install Zod as a dependency in your React project.
   npm install zod
Enter fullscreen mode Exit fullscreen mode
  1. Define a Zod Schema: Create a Zod schema to define the shape and validation rules for your form data. For example, create a file named schemas.js:
   // schemas.js
   import { z } from 'zod';

   export const loginSchema = z.object({
     email: z.string().email('Invalid email address'),
     password: z.string().min(6, 'Password must be at least 6 characters'),
   });
Enter fullscreen mode Exit fullscreen mode
  1. Create a Form Component: Create a React component for your form, and use the Zod schema for validation. Here's an example:
   // LoginForm.js
   import React from 'react';
   import { useForm } from 'react-hook-form';
   import { loginSchema } from './schemas';

   const LoginForm = () => {
     const { register, handleSubmit, errors } = useForm({
       resolver: async (data) => {
         try {
           // Validate using Zod schema
           await loginSchema.validate(data);
           return {
             values: data,
             errors: {},
           };
         } catch (error) {
           return {
             values: {},
             errors: error.errors.reduce((acc, curr) => {
               acc[curr.path[0]] = curr.message;
               return acc;
             }, {}),
           };
         }
       },
     });

     const onSubmit = (data) => {
       // Handle form submission logic here
       console.log(data);
     };

     return (
       <form onSubmit={handleSubmit(onSubmit)}>
         <label>Email</label>
         <input type="text" name="email" ref={register} />
         {errors.email && <p>{errors.email}</p>}

         <label>Password</label>
         <input type="password" name="password" ref={register} />
         {errors.password && <p>{errors.password}</p>}

         <button type="submit">Submit</button>
       </form>
     );
   };

   export default LoginForm;
Enter fullscreen mode Exit fullscreen mode
  1. Explanation:

    • We use the useForm hook from react-hook-form to manage form state and validation.
    • The resolver function is used to integrate Zod with react-hook-form. It asynchronously validates the form data using the Zod schema.
    • Errors from Zod validation are displayed next to the corresponding input fields.
  2. Usage:
    Import and use the LoginForm component in your main application file (e.g., App.js).

   // App.js
   import React from 'react';
   import LoginForm from './LoginForm';

   const App = () => {
     return (
       <div>
         <h1>Login Form</h1>
         <LoginForm />
       </div>
     );
   };

   export default App;
Enter fullscreen mode Exit fullscreen mode

Now you have a React form using react-hook-form for state management and Zod for validation. Customize the form and validation rules according to your specific requirements.

Top comments (0)