<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Allan Melo</title>
    <description>The latest articles on DEV Community by Allan Melo (@allanmelo).</description>
    <link>https://dev.to/allanmelo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F407107%2F03bd895a-096f-4a45-b4d4-ec27e9473c12.jpg</url>
      <title>DEV Community: Allan Melo</title>
      <link>https://dev.to/allanmelo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/allanmelo"/>
    <language>en</language>
    <item>
      <title>Send emails from a contact form in React with EmailJS and Recaptcha</title>
      <dc:creator>Allan Melo</dc:creator>
      <pubDate>Sun, 02 Aug 2020 23:42:07 +0000</pubDate>
      <link>https://dev.to/allanmelo/send-emails-from-a-contact-form-in-react-with-emailjs-and-recaptcha-1oc</link>
      <guid>https://dev.to/allanmelo/send-emails-from-a-contact-form-in-react-with-emailjs-and-recaptcha-1oc</guid>
      <description>&lt;p&gt;This post will guide you through the process of creating a "contact us" form in React.js, and then sending all the info by mail using a third-party service called EmailJS (&lt;a href="https://www.emailjs.com/" rel="noopener noreferrer"&gt;https://www.emailjs.com/&lt;/a&gt;).&lt;/p&gt;




&lt;h2&gt;
  
  
  The component
&lt;/h2&gt;

&lt;p&gt;First, you need to create a new file in your React codebase. I create it as ContactForm.jsx.&lt;/p&gt;

&lt;p&gt;Import react and add emailJs as a dependency using yarn or npm.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add emailjs-com --dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used Bulma as a framework to build the Contact Form in React (using the rbx lib), but all tags from rbx are sel-explained and can be easily replaced by other components and/or other frameworks you prefer.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import * as emailjs from 'emailjs-com';

import { Field, Label, Control, Input, Button, Icon, Textarea, Notification } from 'rbx';

class ContactForm extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      name: '',
      email: '',
      subject: '',
      message: ''
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.resetForm = this.resetForm.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const { name, email, subject, message } = this.state;
    const templateParams = {
      from_name: name,
      from_email: email,
      to_name: '/*YOUR NAME OR COMPANY*/',
      subject,
      message_html: message,
    };
    emailjs.send(
      'gmail',
      'template_XXXXXXXX',
       templateParams,
      'user_XXXXXXXXXXXXXXXXXXXX'
    )
    this.resetForm();
  };

  resetForm() {
    this.setState({
      name: '',
      email: '',
      subject: '',
      message: '',
    });
  }

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  render() {
    const { name, email, subject, message, sentMessage } = this.state;

    return (
      &amp;lt;form onSubmit={this.handleSubmit}&amp;gt;
        &amp;lt;Field&amp;gt;
          &amp;lt;Label&amp;gt;Name&amp;lt;/Label&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Input
              name="name"
              type="text"
              placeholder="Your first and last name"
              value={name}
              onChange={this.handleChange}
            /&amp;gt;
          &amp;lt;/Control&amp;gt;
        &amp;lt;/Field&amp;gt;
        &amp;lt;Field&amp;gt;
          &amp;lt;Label&amp;gt;Email for contact&amp;lt;/Label&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Input
              name="email"
              type="email"
              placeholder="email@gmail.com"
              value={email}
              onChange={this.handleChange}
            /&amp;gt;
          &amp;lt;/Control&amp;gt;
        &amp;lt;/Field&amp;gt;
        &amp;lt;Field&amp;gt;
          &amp;lt;Label&amp;gt;Subject&amp;lt;/Label&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Input
              name="subject"
              type="text"
              placeholder="What is the subject?"
              value={subject}
              onChange={this.handleChange}
            /&amp;gt;
          &amp;lt;/Control&amp;gt;
        &amp;lt;/Field&amp;gt;
        &amp;lt;Field&amp;gt;
          &amp;lt;Label&amp;gt;Message&amp;lt;/Label&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Textarea
              name="message"
              placeholder="Tell me more about..."
              value={message}
              onChange={this.handleChange}
            /&amp;gt;
          &amp;lt;/Control&amp;gt;
        &amp;lt;/Field&amp;gt;

        &amp;lt;Field kind="group"&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Button color="dark"&amp;gt;Send&amp;lt;/Button&amp;gt;
          &amp;lt;/Control&amp;gt;
          &amp;lt;Control&amp;gt;
            &amp;lt;Button text&amp;gt;Cancel&amp;lt;/Button&amp;gt;
          &amp;lt;/Control&amp;gt;
        &amp;lt;/Field&amp;gt;
      &amp;lt;/form&amp;gt;
    );
  }
}

export default ContactForm;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Configuration
&lt;/h2&gt;

&lt;p&gt;Create a free account on &lt;a href="https://www.emailjs.com/" rel="noopener noreferrer"&gt;https://www.emailjs.com/&lt;/a&gt; , connect your email service on it and get a very simple template. We need this to configure this component with your account data.&lt;/p&gt;

&lt;p&gt;Inside the handler function on handleSubmit(event), you need to change the current "to_name" inside template params by your info. The other params (from_name, from_email, subject, and message_html) works very much like this.props, and can be easily retrieved on Emailjs website to build a template email with other infos you may want to get in your form. You can create your own params or take off those you don't need. &lt;/p&gt;

&lt;p&gt;To use it on your template inside Emailjs, you just need to use curly braces inside the template builder.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv5cu6i63gyx6628w51ct.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fv5cu6i63gyx6628w51ct.png" alt="Alt Text" width="605" height="608"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Then, to send the email with this emailjs component, you need to change the configuration object in this function with your infos.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;emailjs.send(
      'gmail',
      'template_XXXXXXXX',
       templateParams,
      'user_XXXXXXXXXXXXXXXXXXXX'
 )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first parameter is your email service provider name. If you are using Gmail, then use "gmail". You can found it on email services tab.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fq9m6a9lkosgbz4z7wpb4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fq9m6a9lkosgbz4z7wpb4.png" alt="email services" width="800" height="121"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The second parameter is the template ID. You will get this from Dashboard of emailJs once registered.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fh2erkl8uuhq8hf3zdo1j.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fh2erkl8uuhq8hf3zdo1j.jpg" alt="Alt Text" width="800" height="124"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The third parameter is variable templateParam which we created using entered data in the form. Don't change it.&lt;/p&gt;

&lt;p&gt;The last parameter is the User ID in the emailJs dashboard.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftvsi0awuoobtiyi0q2do.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Ftvsi0awuoobtiyi0q2do.jpg" alt="Alt Text" width="800" height="263"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don't forget to create a template on EmailJS.&lt;/p&gt;

&lt;p&gt;I recommend you to check the documentation if you need any help: &lt;a href="https://www.emailjs.com/docs/" rel="noopener noreferrer"&gt;https://www.emailjs.com/docs/&lt;/a&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Extra: build it with Recaptcha!
&lt;/h2&gt;

&lt;p&gt;EmailJS also works with Recaptcha, so you can also embed a Recaptcha verification in your form and protect it from robots or spammers by usign the React Recaptcha.&lt;/p&gt;

&lt;p&gt;To make this works, you need to go to Recaptcha and get a SITE_KEY for you. Also, if you are testing it in your local env, don't forget to add "localhost" as a valid domain - so you can make all the test before going to production.&lt;/p&gt;

&lt;p&gt;After that, go to EmailJS website and check your template. You will find a tab where you can activate the Recaptcha on it. You just need to follow their instructions to put your keys to work.&lt;/p&gt;

&lt;p&gt;So ok... Now, how can we render this Recaptcha on our website?&lt;/p&gt;

&lt;p&gt;To make Recaptcha works with React I found the react-recaptcha lib. For me, this was easy to work than the official react-recaptcha-google. So, just go for it and add this as a dependency:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add react-recaptcha
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To make it work properly, you need to add this fragment in the &lt;/p&gt; of your original index.html, inside the public folder:&lt;br&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src="https://www.google.com/recaptcha/api.js" async defer&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Then put this piece where you want to render it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Recaptcha
  sitekey="YOUR_SITE_KEY"
   render="explicit"
    onloadCallback={this.recaptchaLoaded}
    verifyCallback={this.verifiedRecaptcha}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside the constructor(props), add this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recaptchaLoad: false,
isVerified: false,
/* and this... */
this.recaptchaLoaded = this.recaptchaLoaded.bind(this);
this.verifiedRecaptcha = this.verifiedRecaptcha.bind(this);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then use these two elements inside your component to check if Recaptcha loaded and if the user checked it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;recaptchaLoaded() {
  this.setState({ recaptchaLoad: true });
}

verifiedRecaptcha(response) {
  if (response) {
    this.setState({ isVerified: true });
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used both components to prevent the user to send an email without check the recaptcha, so you can change the handleSubmit(event) above by that one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;handleSubmit(event) {
    const { recaptchaLoad, isVerified } = this.state;
    event.preventDefault();
    if (recaptchaLoad &amp;amp;&amp;amp; isVerified) {
      const { name, email, subject, message } = this.state;
      const templateParams = {
        from_name: name,
        from_email: email,
        to_name: '/*YOUR NAME OR COMPANY*/',
        subject,
        message_html: message,
      };
      emailjs.send(
        'gmail',
        'template_XXXXXXXX',
         templateParams,
        'user_XXXXXXXXXXXXXXXXXXXX'
      );
      alert('Your message has been sent successfully. We will contact you soon.');
      this.resetForm();
    } else {
      alert('Please check the Recaptcha before sending your message');
    }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that it!&lt;/p&gt;

&lt;p&gt;I hope this post has helped you.&lt;/p&gt;

&lt;p&gt;If it doesn’t render, after all the steps, it’s worth taking a look at the react-recaptcha documentation or the Google Recaptcha documentation, as the html element may have been modified.&lt;/p&gt;

&lt;p&gt;This post was created based on this another one (&lt;a href="https://medium.com/@eesh.t/send-email-using-emailjs-and-react-form-9993bb6929d8" rel="noopener noreferrer"&gt;https://medium.com/@eesh.t/send-email-using-emailjs-and-react-form-9993bb6929d8&lt;/a&gt;), but using Bulma as a framework and using Recaptcha to prevent abuse.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>frontend</category>
    </item>
  </channel>
</rss>
