Create React contact form and send email with EmailJS

How-to-create-React-contact-form-and-send-email-with-emailjs

Creating a contact form with EmailJS in a React application involves a few steps. EmailJS is a service that allows you to send emails directly from the client-side using JavaScript. Here’s a step-by-step guide:

Step 1: Set Up Your React App

Assuming you have a React app already set up, if not, you can create one using:

npx create-react-app my-emailjs-app
cd my-emailjs-app

Step 2: Install EmailJS Library

Install the EmailJS library using npm or yarn:

npm install emailjs-com

or

yarn add emailjs-com

Step 3: Set Up an EmailJS Account

Go to EmailJS and sign up for an account. Once logged in, create a new email service and template.

Step 4: Get Your EmailJS Service ID and Template ID

After creating a service and template, you’ll need to get the Service ID and Template ID. You can find these in the EmailJS dashboard under the “Email Services” and “Email Templates” sections.

Step 5: Create a Contact Form Component

Create a new component for your contact form, for example, ‘ContactForm.js’.

// ContactForm.js
import React, { useState } from 'react';
import emailjs from 'emailjs-com';

const ContactForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');

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

    // EmailJS parameters
    const templateParams = {
      from_name: name,
      from_email: email,
      message,
    };

    // EmailJS API call
    emailjs
      .send(
        'YOUR_SERVICE_ID', // Replace with your EmailJS Service ID
        'YOUR_TEMPLATE_ID', // Replace with your EmailJS Template ID
        templateParams,
        'YOUR_USER_ID' // Replace with your EmailJS User ID
      )
      .then(
        (response) => {
          console.log('Email sent successfully:', response);
        },
        (error) => {
          console.error('Email send failed:', error);
        }
      );
  };

  return (