Integrating a Contact Form with EmailJS in React by@terieyenike

Integrating a Contact Form with EmailJS in React

React is a front-end library for building user interfaces for front end applications. EmailJS is a service that helps to send emails using client-side applications like React, Vue, and Angular, with no server during configuration and setup. In this tutorial, you’ll learn how to connect React with EmailJS to receive user messages on your website or mobile applications without the stress of building from scratch. The first step of building a new project is to have the tools for development that make building a breeze.
image
Teri Eyenike HackerNoon profile picture

Teri Eyenike

I am a frontend developer with a particular interest in making things simple and usable.

github social icontwitter social iconlinkedin social icon


React is a front-end library for building user interfaces for front-end applications. Also, React is helpful when making your applications as it uses reusable components.


The question that has always existed for front-end developers is how to handle requests from form data without writing or having knowledge of the backend functionalities. Building a backend server can be tedious, and using a third-party service is required for this task to ease the pain of writing logic.


What is EmailJS?

EmailJS is a service that helps to send emails using client-side applications like React, Vue, and Angular, with no server during configuration and setup.


In this tutorial, you’ll learn how to connect a front-end library, React, with EmailJS to receive user messages on your website or mobile applications without the stress of building from scratch.


Demo

Get a head start with the starter code in this repository or create a new React application.


Prerequisites

To follow through with the tutorial, you need to have the following:


Getting Started

The first step of building a new project is to have the tools for development that make building a breeze. In your terminal, run this command:


npx create-react-app react-contact-form-with-emailjs


The command above creates the boilerplate using the create-react-app command that has all the files and packages for the React app.


Installing EmailJS

As a dependency, run the command to install EmailJS SDK into the React app.


npm install @emailjs/browser

Running the Project

To run the React application, navigate to the project directory and run the development server that ships with the hot reload feature, which, in turn, updates the application with any change made during development.


Run this command:


cd react-contact-form-with-emailjs

npm start


The application is accessible on http://localhost:3000.


Creating the Contact Form

Collecting and receiving responses from your users through the contact form is a vital feature that a website needs to have, as it makes you trustworthy in the eyes of visitors.


So, let’s create the contact form. In your App.js file, copy and paste the following code:


// src/App.js

import React from 'react'
import './App.css';

function App() {
  return (
    <div>
      <h1>Contact Form</h1>
      <form className='cf'>
        <div className='half left cf'>
          <input type='text' placeholder='Name' name='user_name' />
          <input type='email' placeholder='Email address' name='user_email' />
        </div>
        <div className='half right cf'>
          <textarea name='message' type='text' placeholder='Message'></textarea>
        </div>
        <input type='submit' value='Submit' id='input-submit' />
      </form>
    </div>
  );
}

export default App;


Styling the Contact Form

The application user interface needs to look beautiful for users, so in the App.css file, copy and paste the following code:


// src/App.css

@import url(https://fonts.googleapis.com/css?family=Merriweather);
html,
body {
  background: #f1f1f1;
  font-family: 'Merriweather', sans-serif;
  padding: 1em;
}

h1 {
  text-align: center;
  color: #a8a8a8;
}

form {
  max-width: 600px;
  text-align: center;
  margin: 20px auto;
}

input,
textarea {
  border: 0;
  outline: 0;
  padding: 1em;
  border-radius: 8px;
  display: block;
  width: 100%;
  margin-top: 1em;
  font-family: 'Merriweather', sans-serif;
  resize: none;
}

#input-submit {
  color: white;
  background: #e74c3c;
  cursor: pointer;
}

#input-submit:hover {
  box-shadow: 0 1px 1px 1px rgba(0, 0, 0, 0.2);
}

textarea {
  height: 126px;
}

.half {
  float: left;
  width: 48%;
  margin-bottom: 1em;
}

.right {
  width: 50%;
}

.left {
  margin-right: 2%;
}

@media (max-width: 480px) {
  .half {
    width: 100%;
    float: none;
    margin-bottom: 0;
  }
}

.cf:before,
.cf:after {
  content: ' ';
  display: table;
}

.cf:after {
  clear: both;
}


The page should look like this with everything done right:

image


Setup EmailJS

With the completion of the contact form page without any functionalities to send messages, let’s set up the service that will send the content of the form to your email.


Add an Email Service

This section is about the integration between EmailJS and your email server. On your EmailJS dashboard, pick the Gmail service from the Email Services tab, which should open a new page called config service.


image

Next, change the name and service id parameters. The service id will be used later while initializing the contact form to connect it to EmailJS. Make sure to click the Connect Account and Create Service button to confirm your changes.


image


Creating an Email Template

The email template is essential when you want to include the email's subject, the content it will contain, and its destination in your inbox when a user sends a message from your website's client-side.


On the dashboard, click the Email Template tab and Create New Template.


Next, you have to click the Settings tab and change the Name and Template ID to anything you so desire. The template ID will be used later, as shown in the image below:


image


Heading back to the Content tab, the values inside the curly brackets are dynamic variables that should have the same value as defined in the <form> element in the contact form, like the message, user_name, and user_email.


Creating the Environment Variables

The environment variables .env is a file that stores your public keys and other values you wish not to share and is private to you alone.


In the root of your project directory, create a file, .env, and paste the following:


// .env

REACT_APP_TEMPLATE_ID=TEMPLATE_ID
REACT_APP_SERVICE_ID=SERVICE_ID
REACT_APP_PUBLIC_KEY=API_PUBLIC_KEY


For the public key, you can find it by clicking the Account tab and copying the value as shown in the public key section:


image


Initialize EmailJS

In the React application, import the installed package, @emailjs/browser package.


Copy and paste the following:


// src/App.js

import React from 'react'
import emailjs from '@emailjs/browser';

function App() {
  return (
    <div>
      // form element
    </div>
  );
}

export default App;


Handling Form Submission

The useRef hook handles contact form submission.


Copy and update the code in theApp.js file:


// src/App.js

import React, { useRef } from 'react';
// imports

function App() {
  const form = useRef();

  const sendEmail = (e) => {
    e.preventDefault();
    emailjs
      .sendForm(
        process.env.REACT_APP_SERVICE_ID,
        process.env.REACT_APP_TEMPLATE_ID,
        form.current,
        process.env.REACT_APP_PUBLIC_KEY
      )
      .then(
        (result) => {
          alert('message sent successfully...');
          console.log(result.text);
        },
        (error) => {
          console.log(error.text);
        }
      );
  };

  return (
    <div>
      <h1>Contact Form</h1>
      <form className='cf' ref={form} onSubmit={sendEmail}>
        // div container with input element
      </form>
    </div>
  );
}

export default App;


The following happens in the code above:

  • The useRef hook is imported and initialized with a variable called form
  • The hook, useRef, is used as a reference and assigned to the <form> element
  • On the sendEmail function, the form has the preventDefault method that stops the page from refreshing
  • Still, in the sendEmail function, the sendForm function is invoked and initialized with the service ID, template ID, the form .current property of the ref, and the public key
  • A callback function for the success and failure cases that occurs with the .then() method


Now let’s see the result of this project:


image

Confirmation Email

image

Conclusion

Using EmailJS for handling data requests on the client-side of your application is an excellent way to receive responses from a contact form. EmailJS provides other features to explore and gives you a robust experience without ever building your server or having knowledge of backend development. It does everything for you under the hood.


Have you used EmailJS before? What do you think about my approach above? Let us know in the comments below!



react to story with heart
react to story with light
react to story with boat
react to story with money

Related Stories

L O A D I N G
. . . comments & more!