Raddy Website Design & Development Tutorials

React Newsletter Signup Form Tutorial + reCAPTCHA | Mailer Lite

By Raddy in ReactJs ·

In this tutorial, learn how to create a dynamic React newsletter signup form with added security using reCAPTCHA. Perfect for developers looking to implement a robust newsletter subscription feature.

Code:

import React, { useState } from 'react'
import ReCAPTCHA from "react-google-recaptcha";
import './App.css'

function App() {
  const [email, setEmail] = useState("");
  const [errorMessage, setErrorMessage] = useState("");
  const [successMessage, setSuccessMessage] = useState("");

  const recaptchaRef = React.createRef();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrorMessage("");
    setSuccessMessage("");

    const recaptchaValue = recaptchaRef.current.getValue();

    if(!recaptchaValue) {
      setErrorMessage("Please verify the Captcha.");
    } else {


    try {
      const response = await fetch(
        "https://connect.mailerlite.com/api/subscribers",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Accept": "application/json",
            Authorization: `Bearer YOUR_API_TOKEN`
          },
          body: JSON.stringify({
            email: email,
            groups: ["117872522076096341"]
          })
        }
      )

      const data = await response.json();
      console.log(data);

      if(data.errors) {
        setErrorMessage(data?.message);
        return;
      }

      setSuccessMessage("Thank you for joining our newsletter!");
    } catch (error) {
      console.error(error);
      setErrorMessage("Failed to subscribe. Please try again later.")
    }

    }

  }

  return (
    <>
      <form onSubmit={handleSubmit}>

        {errorMessage && <p className='error'>{errorMessage}</p>}
        {successMessage && <p className='success'>{successMessage}</p>}

        <input 
        type='email'
        value={email}
        placeholder='Email...'
        onChange={(e) => setEmail(e.target.value)}
        required
        />

        <ReCAPTCHA ref={recaptchaRef} sitekey='6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'/>

        <button type='submit'>Subscribe</button>
      </form>
    </>
  )
}

export default App

Basic CSS Styles:

form, input, button {
  margin: 0;
  padding: 0;
  border: 0;
  font-family: Arial, sans-serif;
  box-sizing: border-box;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  width: 300px;
}

button[type="submit"] {
  background-color: #0069ca;
  border: 1px solid #ccc;
  color: #fff;
  border: none;
  cursor: pointer;
  border-radius: 0;
}

.error {
  color: red;
}

.success {
  color: green;
}

Leave a Reply

Your email address will not be published. Required fields are marked *