DEV Community

Dante Bhang
Dante Bhang

Posted on • Edited on

Create a contact form with EmailJS and React hooks

What is EmailJS?

EmailJS is a free and secure client-side service that allows you to generate custom emails from your application! I will explain step by step how I implemented EmailJS into my React portfolio with this simple demo.

EmailJS Set up

First, you have to make an account at https://www.emailjs.com/
From there under Email Services located at side nav bar, click Add New Service under the header “Email Services”.

Add new service

A pop up modal will appear where you can choose your email service to connect from. For this demo, I just connected my personal gmail account. Next, name your service and service ID. Note that the service ID will be important later when we code so I recommend renaming it to fit your needs. Finally connect your email account and create your service. I suggest keeping the “send test email” checked as EmailJS will send you a test email to ensure everything is in working order!

Name ServiceID

The final set up will be the create an email template. Navigate to "Email Templates" in the side nav bar and create a new template. For this demo, I kept it simple so the only fields I'll add is the contact's name, message and email.

Create template

Notice that the properties I wanted (name, message, email) are in double curly brackets. This is the object keys we will implement later in our code! Once you have the format you want, navigate to settings and name your template ID.

Name template ID

Just like the service ID we will utilize this ID later in our code. Make sure to save your changes here! Last ID we need is our User ID. You can find it under Integration in the nav bar under API keys.

User ID

Let's finally get to the fun part. Our React implementation!

React Set Up
First, lets create a React act. Run create-react-app in your terminal to generate a react starter scaffold.

Next, run npm i emailjs-com to install the EmailJS library (make
sure you are in your app directory).

I started by creating a Contact.js component to create a simple contact form in Bootstrap5. I added a link and script in index.html under the public directory.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description"  content="EmailJS Demo" />
    <!-- Bootstrap Link -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>EmailJS Demo</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <!-- Bootstrap Script -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <div id="root"></div>

  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This seemed to work best for me but you can see other implementations to set up Boostrap5 here.

If you create a new component like I did, make sure to import the file and add it to App.js!

import React from "react";
import Contact from "./Contact";

function App() {

    return(
        <div>
            <Contact />
        </div>
    )
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Contact Form

Here is how I created my contact form with the fields I wanted: Name, email and message with a simple Send button in Contact.js

import React from "react";


function Contact() {


    return (
        <div className="row m-5">
            <div className="col-md-6 col-md">
                <h2>Contact</h2>
                <p>I would love to connect. Send me an email!</p>
                <form >
                    <div className="row">
                        <div className="col-sm-6 form-group">
                            <label htmlFor="name">Name:</label>
                            <input
                                type="text"
                                className="form-control"
                                name="name"
                                required
                            />
                        </div>
                        <div className="col-sm-6 form-group">
                            <label htmlFor="email">Email:</label>
                            <input
                                type="email"
                                className="form-control"
                                name="email"
                                required
                            />
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12">
                            <label htmlFor="message">Message:</label>
                            <textarea
                                className="form-control"
                                type="text"
                                name="message"
                                maxLength="6000"
                                rows="7"
                                required
                            ></textarea>
                        </div>
                    </div>
                    <div className="row mt-2">
                        <div className="col-sm-12 form-group">
                            <button type="submit" className="btn btn-primary">
                                Send
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
}

export default Contact;

Enter fullscreen mode Exit fullscreen mode

Contact form should now look like this!

contact form

EmailJS integration

Now lets import useState from react and emailjs at the top of Contact.js

import React, { useState } from "react";
import * as emailjs from "emailjs-com";
Enter fullscreen mode Exit fullscreen mode

Next, we will create our initial form state of our contact form properties which starts as blank (empty quotes). Then create an event handler to handle each change for name, email and message.

function Contact() {

    const initialFormState = {
        name: "",
        email: "",
        message: "",
    };

    const [contactData, setContactData] = useState({ ...initialFormState });

    const handleChange = ({ target }) => {
        setContactData({
            ...contactData,
            [target.name]: target.value,
        });
    };
//simplified for brevity
......
}
Enter fullscreen mode Exit fullscreen mode

Next we create our submit handler which does all the work to handle our contact form submission. Here you input your service ID, template ID, and User ID. (Be sure to put in quotes and remove curly braces).

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

        emailjs
            .sendForm(
                {Service ID in quotes},
                {Template ID in quotes},
                e.target,
                {USER ID in quotes},
            )
            .then(
                (result) => {
                    console.log(result.text);
                },
                (error) => {
                    console.log(error.text);
                },
            );

        //reset the form after submission
        setContactData({ ...initialFormState });
    };

Enter fullscreen mode Exit fullscreen mode

Now with all your event handlers created, be sure to add value and onChange properties in your input and text area tags on the contact form along with onSubmit in your form tag.

And that is it! Here is what the final component looks like:

import React, { useState } from "react";
import * as emailjs from "emailjs-com";

function Contact() {

    const initialFormState = {
        name: "",
        email: "",
        message: "",
    };

    const [contactData, setContactData] = useState({ ...initialFormState });

    const handleChange = ({ target }) => {
        setContactData({
            ...contactData,
            [target.name]: target.value,
        });
    };

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

        emailjs
            .sendForm(
                "emailjs_demo",
                "demo_template",
                e.target,
                "user_demoblahblahblah",
            )
            .then(
                (result) => {
                    console.log(result.text);
                },
                (error) => {
                    console.log(error.text);
                },
            );

        //reset the form after submission
        setContactData({ ...initialFormState });
    };

    return (
        <div className="row m-5">
            <div className="col-md-6 col-md">
                <h2>Contact</h2>
                <p>I would love to connect. Send me an email!</p>
                <form onSubmit={handleSubmit}>
                    <div className="row">
                        <div className="col-sm-6 form-group">
                            <label htmlFor="name">Name:</label>
                            <input
                                type="text"
                                className="form-control"
                                name="name"
                                value={contactData.name}
                                onChange={handleChange}
                                required
                            />
                        </div>
                        <div className="col-sm-6 form-group">
                            <label htmlFor="email">Email:</label>
                            <input
                                type="email"
                                className="form-control"
                                name="email"
                                value={contactData.email}
                                onChange={handleChange}
                                required
                            />
                        </div>
                    </div>
                    <div className="row">
                        <div className="col-sm-12">
                            <label htmlFor="message">Message:</label>
                            <textarea
                                className="form-control"
                                type="text"
                                name="message"
                                maxLength="6000"
                                rows="7"
                                value={contactData.message}
                                onChange={handleChange}
                                required
                            ></textarea>
                        </div>
                    </div>
                    <div className="row mt-2">
                        <div className="col-sm-12 form-group">
                            <button type="submit" className="btn btn-primary">
                                Send
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    );
}

export default Contact;

Enter fullscreen mode Exit fullscreen mode

Be sure to make a test email to see if it works! It should be sent directly to your inbox and look something like this:

Test email

I hope you enjoyed my breakdown of how to make a functional contact form using React's best practices! Feel free to check out the full repo here.

Top comments (1)

Collapse
 
xr0master profile image
Sergey Khomushin

Thanks for your wonderful article!