Send an email using React.js + Express.js

I created a web application using React.js in ES6. Currently I want to create a Contact Us base page and you want to send an email. I am new to React and have just discovered that I really cannot send an email using React. I am following a tutorial with nodemailerand express-mailer, but with some difficulties, integrated sample code with my React files. In particular, the call works node expressFile.js, but I have no idea how to associate this with my React interface.

Nodemailer: https://github.com/nodemailer/nodemailer

Express mail: https://www.npmjs.com/package/express-mailer

The My React component for the form is shown below. How to write an Express file to be called from a method contactUs()in my React component? Thank!

import React from 'react';
import {
  Col,
  Input,
  Button,
Jumbotron
} from 'react-bootstrap';

class ContactView extends React.Component{
  contactUs() {
    // TODO: Send the email here

  }
  render(){
    return (
      <div>
    <Input type="email" ref="contact_email" placeholder="Your email address"/>
    <Input type="text" ref="contact_subject" placeholder="Subject"/>
    <Input type="textarea" ref="contact_content" placeholder="Content"/>
    <Button onClick={this.contactUs.bind(this)} bsStyle="primary" bsSize="large">Submit</Button>
  </div>
)
  }
};

export default ContactView;
+4
source share
2 answers

When the button is pressed, execute an ajax POST request to your express server, i.e. "/ contactus". / contactus can receive email, subject and content from mail data and send a function to mail.

In reagent:

$.ajax({
    url: '/contactus',
    dataType: 'json',
    cache: false,
    success: function(data) {
        // Success..
    }.bind(this),
    error: function(xhr, status, err) {
        console.error(status, err.toString());
    }.bind(this)
});

In express, add the nodemailer code to the express mail handler:

app.post('/contactus', function (req, res) {
    // node mailer code
});
+10
source

@ ryan-jenkin is completely right.

, /jQuery , fetch api. , , , .

(React):

handleSubmit(e){
  e.preventDefault()

  fetch('/contactus', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      email: this.state.email,
      // then continue this with the other inputs, such as email body, etc.
    })
  })
  .then((response) => response.json())
  .then((responseJson) => {
    if (responseJson.success) {
      this.setState({formSent: true})
    }
    else this.setState({formSent: false})
  })
  .catch((error) => {
    console.error(error);
  });
}

render(){
  return (
    <form onSubmit={this.handleSubmit} >
      <input type="text" name="email" value={this.state.email} />
      // continue this with other inputs, like name etc
    </form>
  )
}
+4

All Articles