Send an Email Using React.js + Express.js Send an Email Using React.js + Express.js express express

Send an Email Using React.js + Express.js


When the button is clicked, execute an ajax POST request to your express server, i.e "/contactus". /contactus can fetch the email, subject, and content out of the post data and send to the mail function.

In React:

$.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 within an express post handler:

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


@ryan-jenkin is completely correct.

Alternatively, if you don't have / want jQuery as a dependency, you can use the native fetch api. Also, I typically set up my form so each input has a state, then use that state in the stringified blob.

Client-side (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>  )}