DEV Community

Cover image for How to create Subscribe to Newsletter with Reactjs and Supabase
Adijat Motunrayo Adeneye
Adijat Motunrayo Adeneye

Posted on

How to create Subscribe to Newsletter with Reactjs and Supabase

Table of Contents

  1. Introduction
  2. Setting Up the Project
  3. Configuring the Newsletter Subscription Table in Supabase
  4. Building the React Component
  5. Connecting React project to Supabase
  6. Conclusion

Introduction

Subscribe to newsletter page allow users to input their emails in order to get newsletters from their favorite websites. For this project we will be using Reactjs and Supabase to implement this feature. Supabase is an open source tool that is alternative to Firebase, it is used in database management, authentication and real time updates because it provides hosted PostgreSQL database and also allows easy email validation.


Setting up the project

  • 1. Node.js Installation

Check if Node.js is installed in our project by running this command below.

node -v
Enter fullscreen mode Exit fullscreen mode

OR

npm -v
Enter fullscreen mode Exit fullscreen mode

This command will output the version installed, if not, head to the Node.js website and download and install Node.js. The installment package is accompanied with a Node Package Manager(NPM).

  • 2. Initialize Reactjs project

Set up Reactjs by installing it using Vite using this command on the terminal

npm create vite@latest

Enter fullscreen mode Exit fullscreen mode

The following prompt will pop up and answer the question.


√ Project name: ... newsletter-app
√ Select a framework: » React
√ Select a variant: » JavaScript + SWC
Enter fullscreen mode Exit fullscreen mode

Follow the instruction below

cd newsletter-app
npm install
Enter fullscreen mode Exit fullscreen mode

First you sign up for the supabase account, if you don't have one and create a new project. Run the command below to install the supabase client on the React project.

npm install @supabase/supabase-js
Enter fullscreen mode Exit fullscreen mode

After the installation, check the package.json to see if it is properly installed.


Configuring the Newsletter Subscription Table in Supabase

  • Navigate to the Supabase dashboard after you have created a project, go the the table editor to create a new table.

Table editor

  • Name the table newsletter and add the following columns

    • 1. id: Primary key, UUID, default as uuid_generate_v4().
    • 2. email: Text, unique, required.
    • 3. created_at: Timestamp, default as now().

newsletter table

  • Allow the Supabase to configure public access This can be set up in the the policy page under configuration, search for the table newsletter and create a policy.

Policy table


Building the React Component

  • Create a folder called components in the root folder and set up the NewsletterForm.jsx file in the components.
// src/components/NewsletterForm.jsx,  
import React, {useState} from 'react';  

const NewsletterForm = () => { 
const [email, setEmail] = useState(""); 
  const handleSubmit = async (e) => {  
    e.preventDefault(); 
  };  

  return (  
    <form onSubmit={handleSubmit}>  
       <h1>Join our Newsletter</h1>
       <h2>Enter your email to receive latest news. </h2>      
         {error && <p style={{ color: "red" }}>{error}</p>}
         {success && <p style={{ color: "green" }}>{success}</p>}
       <label htmlFor="email" className="sr-only"></label>
       <input  
        type="email"  
        value={email}  
        onChange={(e) => setEmail(e.target.value)}  
        placeholder="Your email"  
        required  
      />  
      <button type="submit">Subscribe</button>  
    </form>  
  );  
};  

export default NewsletterForm;
Enter fullscreen mode Exit fullscreen mode
  • Remove all the unneccessary code in the App.jsx and import the NewsletterForm.jsx.
import './App.css';
import NewsletterForm from './NewsletterForm';

function App() {
  return (
    <div className="App">
     <NewsletterForm/>    
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  • Style the Components by creating styles in the index.css file


* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  background-color: #030303;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  font-family: system-ui, "Open Sans", "Helvetica Neue", sans-serif;
}
form {
  display: flex;
  align-items: center;
  flex-direction: column;
  padding: 1.5rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}
h1 {
  margin-bottom: 0.5rem;
  font-size: 1.8rem;
  color: #111331;
}
h2 {
  font-size: 1rem;
  font-weight: 400;
  margin-bottom: 1rem;
  text-align: center;
}

input[type="email"] {
  width: 100%;
  padding: 0.75rem;
  margin-bottom: 1rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
  transition: border 0.3s ease;
}

input[type="email"]:focus {
  border-color: #007bff;
  outline: none;
}

button {
  background-color: #007bff;
  color: white;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  margin-bottom: 0.5rem;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0056b3;
}
button:focus {
  border-radius: 20px;
  transition: border-radius 0.5s ease;
}
p {
  margin: 0.5rem 0;
  font-size: 0.9rem;
}

p[style*="color: red"] {
  font-weight: bold;
}

p[style*="color: green"] {
  font-weight: bold;
}

Enter fullscreen mode Exit fullscreen mode

Here is the output

Output


Connecting React project to Supabase

  • Add the Supabase client by set up the supabaseClient.js file to add the SUPABASE_URL and the SUPABASE_ANON_KEY.
import { createClient } from "@supabase/supabase-js";

const SUPABASE_URL = "https://esqaciqvjfarmopjzomj.supabase.co";
const SUPABASE_ANON_KEY ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVzcWFjaXF2amZhcm1vcGp6b21qIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzQzNjA4NDksImV4cCI6MjA0OTkzNjg0OX0.Q2A5fbvdebid_Wsbm5r58Ej7xrLKCL4_4ULuu-kA6Ro";

export const supabase = createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
Enter fullscreen mode Exit fullscreen mode
  • Updating the NewsletterForm.jsx to have the email store in the database.
// src/NewsletterForm.js
import { useState} from "react";  
import { supabase } from "../supabaseClient";

const NewsletterForm = () => {
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setSuccess("");

    // Check if email is valid
    if (!/\S+@\S+\.\S+/.test(email)) {
      setError("Please enter a valid email");
      return;
    }

    // Insert email into Supabase
    const { error: insertError } = await supabase
      .from("newsletters")
      .insert([{ email }]);

    if (insertError) {
      setError("Error subscribing to newsletter: " + insertError.message);
    } else {
      setSuccess("Thank you for subscribing!");
      setEmail(""); // Clear the input field
    }

    // Clear messages after 3 seconds  
    setTimeout(() => {  
      setError("");  
      setSuccess("");  
    }, 3000);
  };

  return (
    <form onSubmit={handleSubmit}>
      <h1>Join our Newsletter</h1>
      <h2>Enter your email to receive latest news. </h2>
      {error && <p style={{ color: "red" }}>{error}</p>}
      {success && <p style={{ color: "green" }}>{success}</p>}
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Your email"
        required
      />
      <button type="submit">Subscribe</button>
    </form>
  );
};

export default NewsletterForm;
Enter fullscreen mode Exit fullscreen mode

Output

Email Table

Check the link below to check the demo
Demo


Conclusion

With this guide, you have been to create a subscribe to newsletter with Supabase to have the emails subscribed stored in the database and can be used later on.

Top comments (0)