0

Need some quick guidance regarding the newsletter button in react webpage. I wanna make a newsletter button that accepts, emails from users and stores them in a spreadsheet. Basically, I need some code guidance such that when someone enters their email and clicks submit button. They will get the template email like 'Thanks for subscribing to our newsletter and company email and we get their email in the spreadsheet.

Daksh967
  • 1
  • 1

1 Answers1

0

In order for this to work you would have your React.js frontend that would get the e-mail address from the user and send a request to your backend service containing that e-mail address. This could look similar to this.

import { useState } from "react";
import "./styles.css";

function isValidEmailAddress(email) {
  // validate here
  return true;
}

export default function App() {
  const [address, setAddress] = useState("");

  async function subscribeNewsletter() {
    if (isValidEmailAddress(address)) {
      try {
        const response = await fetch("https://your-backend/subscription", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            email: address
          })
        });
        // check if request was successful (codes 200-299)
        // in this implementation we expect code "201 Created"
        if (!response.ok) {
          const parsed = JSON.parse(response.body);
          // show error message received from backend
          alert(parsed.msg);
        } else {
          alert("Subscribed.");
        }
      } catch (error) {
        alert("Subscription failed");
      }
    }
  }

  return (
    <div className="App">
      <input onChange={(e) => setAddress(e.target.value)} value={address} />
      <button onClick={() => subscribeNewsletter()}>Subscribe</button>
    </div>
  );
}

See CodeSandbox for a minimal working demo of the frontend.

Within your backend you have to handle the request to the /subscription endpoint. In a handler you will probably validate the email address again and then write it into a database or spreadsheet (if you really want to use spreadsheets which I would not recommend). Last but not least you need to send the welcome email. The easiest way to do this is to use a 3rd party API or you use something like SMTP JS to send an email. What you will need in that case is a SMTP server. Have a look on this thread for more details.
The backend service could then look similar to this.

Note: this is not a perfect implementation but a skeleton that should help you getting started.

import express from "express";

// create app
var app = express();
// middleware to parse json
app.use(express.json())

app.get('/', function (req, res) {
    // serve your react application
    res.sendFile("index.html");
});

app.post("/subscription", function (req, res) {
    const emailAddress = req.body.email;
    if (!isValidEmailAddress(emailAddress)) {
        // malformed email address
        res.status(400).send({
            msg: "email address is invalid"
        })
    }
    insertNewSubscriber(emailAddress);
    sendWelcomeEmail(emailAddress);
    // resource subsription has been created
    res.status(201).send();
});

// listen for request on port 3000
const port = 3000;
app.listen(port, () => {
    console.log(`Listening on port ${port}`);
});

function isValidEmailAddress(email) {
    // validate here
    return true;
}

function insertNewSubscriber(email) {
    // write to database/ file/ spreadsheet etc.
}

function sendWelcomeEmail(email) {
    // send email e.g. using 3rd party API
}
Mushroomator
  • 6,516
  • 1
  • 10
  • 27