Written by: Geoffrey Callaghan

React Hook Form with Yup and TypeScript

React Hook Form With Yup And Typescript

Combining React Hook Form with Yup and TypeScript allows for efficient form validation and management in React applications. Here’s a step-by-step guide on how to integrate React Hook Form with Yup and TypeScript for robust form handling.

1. Installation

First, you need to install the necessary dependencies:

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

2. Creating a Form Component

Create a form component using React Hook Form and Yup for validation.

Example

// components/MyForm.tsx
import React from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

// Define Yup schema
const schema = yup.object().shape({
  name: yup.string().required('Name is required'),
  email: yup.string().email('Invalid email').required('Email is required'),
});

type FormValues = {
  name: string;
  email: string;
};

const MyForm: React.FC = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    resolver: yupResolver(schema),
  });

  const onSubmit: SubmitHandler<FormValues> = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name:</label>
        <input id="name" type="text" {...register('name')} />
        {errors.name && <p>{errors.name.message}</p>}
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input id="email" type="email" {...register('email')} />
        {errors.email && <p>{errors.email.message}</p>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

3. Using the Form Component

Now, you can use the form component in your application.

Example

// pages/index.tsx
import React from 'react';
import MyForm from '../components/MyForm';

const Home: React.FC = () => {
  return (
    <div>
      <h1>React Hook Form with Yup and TypeScript</h1>
      <MyForm />
    </div>
  );
};

export default Home;

4. Handling Form Submission

You can handle form submission in the onSubmit function passed to handleSubmit.

Example

// components/MyForm.tsx
import React from 'react';
import { useForm, SubmitHandler } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

const schema = yup.object().shape({
  name: yup.string().required('Name is required'),
  email: yup.string().email('Invalid email').required('Email is required'),
});

type FormValues = {
  name: string;
  email: string;
};

const MyForm: React.FC = () => {
  const { register, handleSubmit, formState: { errors } } = useForm<FormValues>({
    resolver: yupResolver(schema),
  });

  const onSubmit: SubmitHandler<FormValues> = (data) => {
    console.log('Submitted:', data);
    // Perform additional actions like API calls, navigation, etc.
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label htmlFor="name">Name:</label>
        <input id="name" type="text" {...register('name')} />
        {errors.name && <p>{errors.name.message}</p>}
      </div>
      <div>
        <label htmlFor="email">Email:</label>
        <input id="email" type="email" {...register('email')} />
        {errors.email && <p>{errors.email.message}</p>}
      </div>
      <button type="submit">Submit</button>
    </form>
  );
};

export default MyForm;

Conclusion

Integrating React Hook Form with Yup and TypeScript enables you to efficiently manage and validate forms in React applications. By defining schemas with Yup, you ensure robust validation, while React Hook Form simplifies form management. This combination allows for a smooth and type-safe form handling experience in your React projects.