How to Integrate EmailJS with a......

How to Integrate EmailJS with a Contact Form in React

How to Integrate EmailJS with a Contact Form in React

In this tutorial, we'll walk you through how to integrate EmailJS with a React contact form to send form submissions to your email and store the details in Supabase. This step-by-step guide will help you capture inquiries from your website users and ensure they are securely delivered to your email inbox and stored in your database.

Prerequisites

Before we start, make sure you have the following:

  • A React application set up.
  • An account with EmailJS.
  • An account with Supabase for database storage.


Step 1: Set Up Your Contact Form

We'll begin by setting up a basic contact form in React. The form will capture the user's name, email, phone number, and inquiry.

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import emailjs from 'emailjs-com';

function Contact() {
  const [formValues, setFormValues] = useState({
    name: "",
    email: "",
    phone: "",
    about: "",
  });

  const [formErrors, setFormErrors] = useState({});
  const [isSubmitted, setIsSubmitted] = useState(false);

  const validate = () => {
    const errors = {};

    if (!formValues.name.trim()) errors.name = "Name is required";
    if (!formValues.email) errors.email = "Email is required";
    else if (!/\S+@\S+\.\S+/.test(formValues.email)) errors.email = "Email is invalid";
    if (!formValues.phone) errors.phone = "Phone number is required";
    else if (!/^\d{10}$/.test(formValues.phone)) errors.phone = "Phone number is invalid";
    if (!formValues.about.trim()) errors.about = "About is required";

    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormValues({ ...formValues, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    setIsSubmitted(true);

    if (validate()) {
      sendEmail();
      storeInSupabase();
      resetForm();
    }
  };

  const sendEmail = () => {
    const templateParams = {
      name: formValues.name,
      email: formValues.email,
      phone: formValues.phone,
      about: formValues.about,
    };

    emailjs.send('your_service_id', 'your_template_id', templateParams, 'your_user_id')
      .then((response) => {
        console.log('Email sent successfully!', response.status, response.text);
      }, (error) => {
        console.error('Failed to send email. Error:', error);
      });
  };

  const storeInSupabase = async () => {
    // Your Supabase insertion logic here
  };

  const resetForm = () => {
    setFormValues({
      name: "",
      email: "",
      phone: "",
      about: "",
    });
    setFormErrors({});
    setIsSubmitted(false);
  };

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        name="name"
        label="Name"
        value={formValues.name}
        onChange={handleChange}
        error={isSubmitted && !!formErrors.name}
        helperText={isSubmitted && formErrors.name}
      />
      <TextField
        name="email"
        label="Email"
        value={formValues.email}
        onChange={handleChange}
        error={isSubmitted && !!formErrors.email}
        helperText={isSubmitted && formErrors.email}
      />
      <TextField
        name="phone"
        label="Phone No."
        value={formValues.phone}
        onChange={handleChange}
        error={isSubmitted && !!formErrors.phone}
        helperText={isSubmitted && formErrors.phone}
      />
      <TextField
        name="about"
        label="About"
        value={formValues.about}
        onChange={handleChange}
        multiline
        rows={4}
        error={isSubmitted && !!formErrors.about}
        helperText={isSubmitted && formErrors.about}
      />
      <button type="submit" disabled={!validate()}>Submit</button>
    </form>
  );
}

export default Contact;

Explanation

  • Form Validation: The form includes basic validation to ensure all fields are filled out correctly.
  • Form Submission: On form submission, the handleSubmit function is called. It validates the form, sends the email using EmailJS, stores the data in Supabase, and resets the form.


Step 2: Setting Up EmailJS

  1. Create an EmailJS Account: If you don't have an EmailJS account, sign up at emailjs.com.
  2. Create a Service: In the EmailJS dashboard, create a new email service.
  3. Create an Email Template: Design an email template that will receive the form data. Use placeholders like {{name}}, {{email}}, {{phone}}, and {{about}}.
  4. Get Your User ID and Service ID: In the EmailJS dashboard, get your user_id, service_id, and template_id and use them in the emailjs.send method.

Share Article:
  • Facebook
  • Instagram
  • LinkedIn
  • Twitter
  • Recent Posts