ReactJS - onSubmit Send email using Sendgrid or something similiar - Stack Overflow

PHOTO EMBED

Thu Aug 06 2020 19:46:51 GMT+0000 (Coordinated Universal Time)

Saved by @keerthanenr #javascript

import React, { Component } from 'react';
import { FormErrors } from './FormErrors';
import './Form.css';

class Form extends Component {
 constructor (props) {
    super(props);
    this.state = {
      fname: '',
      lname: '',
      email: '',
      phone: '',
      formErrors: {fname: '', lname: '', email: '', phone: ''},
      fnameValid: false,
      lnameValid: false,
      emailValid: false,
      phoneValid: false,
      formValid: false
    }


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


    handleUserInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value},
                  () => { this.validateField(name, value) });
  }

  validateField(fieldName, value) {
    let fieldValidationErrors = this.state.formErrors;
    let fnameValid = this.state.fnameValid;
    let lnameValid = this.state.lnameValid;
    let emailValid = this.state.emailValid;
    let phoneValid = this.state.phoneValid;

    switch(fieldName) {
      case 'fname':
        fnameValid = value.match(/^[a-zA-Z]*$/);
        fieldValidationErrors.first = fnameValid ? '' : ' name is invalid. ';
        fieldValidationErrors.first += value.length >= 2 ? '' : ' name should contain at least 2 chars. ';
        break;      
      case 'lname':
        lnameValid = value.match(/^[a-zA-Z]*$/) && value.length >= 2;
        fieldValidationErrors.last = lnameValid ? '' : ' name is invalid. ';
        fieldValidationErrors.last += value.length >= 2 ? '' : ' name should contain at least 2 chars. ';
        break;      
      case 'email':
        emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        fieldValidationErrors.email = emailValid ? '' : ' is invalid. ';
        break;
      case 'phone':
        phoneValid = value.length == 10;
        fieldValidationErrors.phone = phoneValid ? '' : ' should contain 10 digits exactly. ';
        fieldValidationErrors.phone += value.match(/^\d+$/) ? '' : ' should contain numbers only. ';
        break;
      default:
        break;
    }
    this.setState({formErrors: fieldValidationErrors,
                    fnameValid: fnameValid,
                    lnameValid: lnameValid,
                    emailValid: emailValid,
                    phoneValid: phoneValid
                  }, this.validateForm);
  }

  validateForm() {
    this.setState({formValid: this.state.fnameValid && this.state.lnameValid && this.state.emailValid && this.state.phoneValid});
  }

  errorClass(error) {
    return(error.length === 0 ? '' : 'has-error');
  }


  handleSubmit(event) {

        const sgMail = require('@sendgrid/mail');
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
          const msg = {
          to: 'avivday@gmail.com',
          from: 'avivday@gmail.com',
          subject: 'JonesForm',
          text: 'and easy to do anywhere, even with Node.js',
          html: '<strong>and easy to do anywhere, even with Node.js</strong>',
        };
        sgMail.send(msg);
      event.preventDefault();
  }



 render () {
   return (
     <form className="demoForm" onSubmit={this.handleSubmit}>
        <div className="panel panel-default">
          <FormErrors formErrors={this.state.formErrors} />
        </div>

       <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.fname)}"}>
          <input type="text" className="form-control" name="fname"
            placeholder="First Name"
            value={this.state.fname}
            onChange={this.handleUserInput}  />
        </div>        
       <br />
       <div className={"form-group ${this.errorClass(this.state.formErrors.lname)}"}>
          <input type="text" className="form-control" name="lname"
            placeholder="Last Name"
            value={this.state.lname}
            onChange={this.handleUserInput}  />
        </div>
              <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.email)}"}>
          <input type="email" required className="form-control" name="email"
            placeholder="Email"
            value={this.state.email}
            onChange={this.handleUserInput}  />
        </div>
              <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.phone)}"}>
          <input type="text" className="form-control" name="phone"
            placeholder="Phone Number"
            value={this.state.phone}
            onChange={this.handleUserInput}  />
        </div>

       <br/>
        <button type="submit" disabled={!this.state.formValid}>Submit</button>
      </form>
   )
 }
}
export default Form;
content_copyCOPY

https://stackoverflow.com/questions/51429642/reactjs-onsubmit-send-email-using-sendgrid-or-something-similiar