Streamline Form Validation with React Hook Form and implement Email Service using EmailJS

Streamline Form Validation with React Hook Form and implement Email Service using EmailJS

In web development, form validation is a crucial aspect to ensure data accuracy and user experience. React Hook Form is a powerful library that simplifies the process of building robust forms in React applications. Alongside form validation, integrating email services can enhance functionality by enabling automated email notifications.

In this blog post, we will explore how to combine the capabilities of React Hook Form and EmailJS to create a seamless form validation and email service integration.

What is React Hook Form?

React Hook Form is a lightweight and performant library for managing forms in React applications. It simplifies form validation, state management, and submission handling by leveraging React's hooks feature.

Setting up a React Application:

To get started, ensure that you have Node.js and npm (Node Package Manager) installed on your machine. Create a new React application using the following command in your terminal:

npx create-react-app form-validation-email-service

Installing React Hook Form and EmailJS:

Navigate into the project directory and install React Hook Form and EmailJS packages:

cd form-validation-email-service
npm install react-hook-form @emailjs/browser --save

Building a Form with React Hook Form:

In your React component file, import the necessary dependencies:

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

function ContactForm() {
  const { register, handleSubmit } = useForm();

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

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      {/* Form fields */}
    </form>
  );
}

export default ContactForm;

Validating Form Inputs:

React Hook Form offers a simple way to validate form inputs using built-in validation rules or custom functions. Let's add some basic validation to our form fields:

<input
  type="text"
  {...register('name', { required: true })}
/>

<input
  type="email"
  {...register('email', 
    { 
      required: true, 
      pattern: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i 
    }
  )}
/>

Submitting Form Data:

To handle form submission, we'll utilize the handleSubmit function provided by React Hook Form. In the onSubmit callback, we can access the form data and perform further actions:

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

  // Perform additional actions like API calls or email service integration
};

Integrating EmailJS

EmailJS is a service that allows you to send emails directly from the client-side without any server-side code.

Sign up for an account on the EmailJS website and obtain your user ID and template ID. Import the EmailJS library and configure it with your credentials:

import emailjs from '@emailjs/browser';

 const onSubmit = (data) => {
    console.log(data);
    const params = {
        "user_name":data.username, //key value mustbe same as in your template in emailjs
        "user_email":data.email,
        "message": data.message,
    }
    emailjs.sendForm('YOUR_SERVICE_ID', 'YOUR_TEMPLATE_ID', params ,'YOUR_PUBLIC_KEY')
      .then((result) => {
          console.log(result.text);
      }, (error) => {
          console.log(error.text);
      });
  };

You can now test your form by filling in the required fields and submitting it. Ensure that you receive the success message and check the recipient's email inbox for the email notification.

Conclusion

In this blog post, we explored the process of implementing form validation using React Hook Form and integrating an email service using EmailJS. React Hook Form simplified form management by providing an intuitive API for validation and submission handling. By integrating EmailJS, we were able to enhance the functionality by sending automated email notifications to the desired recipient.

Remember to further explore the documentation of React Hook Form and EmailJS to unleash their full potential in your projects. Happy coding!

Did you find this article valuable?

Support Devcon blogs by becoming a sponsor. Any amount is appreciated!