search
HomeWeb Front-endJS TutorialHow to create a newsletter signup form in just minutes with shadcn/UI and Manifest

In der heutigen digitalen Welt ist es von entscheidender Bedeutung, Ihre Ideen schnell testen und mit Ihren Benutzern interagieren zu können, egal ob Sie ein MVP aufbauen, ein Startup gründen oder ein Projekt innerhalb einer engen Frist liefern. Das Erstellen eines Newsletter-Abonnementformulars ist häufig erforderlich, um Ihr Konzept zu validieren, frühe Benutzer einzubinden, eine Community interessierter Personen aufzubauen und Feedback zu sammeln.

schlüsselfertige Lösungen können kostspielig sein, während die Verwendung kostenloser Tools immer noch komplex und zeitaufwändig ist.

In diesem Tutorial zeige ich Ihnen, wie Sie in weniger als 20 Minuten ein Newsletter-Anmeldeformular erstellen. Keine komplexen Konfigurationen, keine Kopfschmerzen. Nur ein Formular mit einem voll funktionsfähigen Abonnementsystem!

Stapel verwendet

  • shadcn/UI: gebrauchsfertige, schön gestaltete Komponenten zum Aufbau des Frontends.
  • Manifest: Der schnellste und einfachste Weg, ein vollständiges Backend zu erstellen, indem Sie einfach eine YAML-Datei füllen.

Am Ende dieses Tutorials verfügen Sie über ein voll funktionsfähiges Formular zum Sammeln Ihrer ersten Abonnenten. Bereit? Auf geht's!

Was ist Manifest?

Manifest ist unser Open-Source-Backend-as-a-Service (BaaS). Es ermöglicht die Erstellung eines vollständigen Backends für Ihre Anwendung.

Durch einfaches Ausfüllen einer einzigen YAML-Datei generieren Sie ein Backend mit einer Datenbank, einer API und einem benutzerfreundlichen Admin-Panel für technisch nicht versierte Administratoren.

Dadurch können Sie sich auf die Entwicklung Ihres Produkts konzentrieren, anstatt sich mit der Backend-Komplexität auseinanderzusetzen.

Heute haben wir gerade unser MVP veröffentlicht und wir zählen auf das Feedback der Community, das uns dabei hilft, das Produkt in die richtige Richtung weiterzuentwickeln.

Manifest ist auf GitHub verfügbar, also geben Sie ihm gerne ein ⭐, wenn Ihnen das Projekt gefällt!

Planung der Schnittstelle

Unser Ziel ist ein einziger Bildschirm, auf dem ein Abonnementfeld und Benachrichtigungsmeldungen angezeigt werden. Es ist einfach, effektiv und funktional. Das bekommen wir:

  • Das Frontend für Abonnenten
  • Das Admin-Panel für die Administratoren

Erstellen des Frontends mit shadcn/UI

Wir beginnen mit der Erstellung des Projekts mit dem Frontend, also dem visuellen Teil unseres Newsletter-Anmeldeformulars.

Ich habe mich für die Verwendung von shadcn/UI mit Next.js entschieden. Führen Sie den folgenden Befehl in Ihrem Terminal aus:

npx shadcn@latest init -d

Sie werden aufgefordert, ein neues Next.js-Projekt zu starten und Ihrem Projekt einen Namen zu geben. Antworten Sie mit „Y“ und nennen Sie es Newsletter-Formular.

Sobald das Projekt erstellt ist, sollten Sie Ihr Frontend mit diesen Dateien bereit haben:

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Starten Sie den Entwicklungsserver, indem Sie Folgendes ausführen: npm run dev.

Klicken Sie im Terminal auf den bereitgestellten Link. Es sollte den NextJS-Begrüßungsbildschirm in Ihrem Standard-Webbrowser unter https://localhost:3000 öffnen.

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Erstellen des statischen Formulars

Lassen Sie uns unser Formular erstellen, indem wir app/page.tsx bearbeiten. Da shadcn mit TailwindCSS funktioniert, verwenden wir seine Klassen, um die gewünschte Schnittstelle zu erstellen. Kopieren Sie den folgenden Code:

export default function Home() {
  return (
    <div classname="w-full lg:grid lg:grid-cols-5 min-h-screen flex sm:items-center sm:justify-center sm:grid">
      <div classname="flex items-center justify-center py-12 col-span-2 px-8">
        <div classname="mx-auto grid max-w-[540px] gap-6">
          <div classname="grid gap-2 text-left">
            <h1 id="Subscribe-to-our-Newsletter">Subscribe to our Newsletter! ?</h1>
            <p classname="text-balance text-muted-foreground">
              Get the latest news, updates, and special offers delivered straight to your inbox.
            </p>
          </div>
          <form classname="grid gap-4">{/* Newsletter form here */}</form>
        </div>
      </div>
      <div classname="hidden bg-muted lg:block col-span-3 min-h-screen bg-gradient-to-t from-green-50 via-pink-100 to-purple-100"></div>
    </div>
  );
}

Sie sollten einen geteilten Bildschirm mit einem Bereich für das Formular auf der linken Seite und einem Farbverlaufsbereich auf der rechten Seite sehen.

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Jetzt fügen wir das Formular hinzu. Es enthält die folgenden Shadcn-Komponenten:

  • Eingabe
  • Schaltfläche

Installieren Sie diese Komponenten über Ihr Terminal mit den folgenden Befehlen:

npx shadcn@latest add input
npx shadcn@latest add button

Importieren Sie dann die Komponenten wie folgt in Ihre page.tsx-Datei:

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

Verwenden Sie diese beiden Komponenten, indem Sie das folgende Snippet in das vorhandene einfügen. Tag:


Sent out weekly on Mondays. Always free.

Sie sollten ein responsives Newsletter-Formular in Ihrem Frontend haben. Nehmen Sie sich einen Moment Zeit, um Ihre Arbeit zu bewundern. Und entspannen Sie sich, unser 20-Minuten-Versprechen gilt weiterhin!

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Erstellen des Backends mit Manifest

Fügen wir das Backend hinzu, um die Abonnenten zu speichern und es Administratoren zu ermöglichen, sie über ein Admin-Panel zu verwalten.

Installieren Sie Manifest im Stammverzeichnis des Projekts mit dem folgenden Befehl:

npx add-manifest

Sobald das Backend installiert ist, sollten Sie die folgenden Dateien in Ihrem Repository sehen:

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Now let’s define our data model. Open the backend.yml file and replace the existing code with this one:

name: Newsletter Form

entities:
  Subscriber:
    properties:
      - { name: email, type: email }

Run the following command to start your server:

npm run manifest

Once your backend is running, the terminal will provide two links:

  • ?️ Admin panel : http://localhost:1111,
  • ? API Doc: http://localhost:1111/api.

Launch the admin panel on your browser and log in with the pre-filled credentials. You should now see an empty list of subscribers.

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

There we have it! In under 3 minutes, We’ve built a full backend for our newsletter subscription form. ?

Connecting Manifest with our frontend

We’ll use Manifest’s SDK to connect the form and add emails directly to the subscribers list from the frontend.

From your project’s root, install the SDK with:

npm i @mnfst/sdk

Let’s add the newsletter subscription functionality to turn the static form into a dynamic one that stores emails using Manifest.

Next.js treats the files in the app directory as Server Components by default. To use interactive features (like React hooks), we need to mark our component as a Client Component.

Add "use client"; at the top of your Home.tsx file:

'use client';

Next, create the handleSubmit function to capture the email and send it to Manifest:

export default function Home() {
  const handleSubmit = (e: React.FormEvent<htmlformelement>) => {
    e.preventDefault();

    const form = e.currentTarget as HTMLFormElement;
    const emailInput = form.querySelector('input[name="email"]') as HTMLInputElement;
    const email = emailInput?.value;

    if (!email) {
      alert('Please enter a valid email.');
      return;
    }

    const manifest = new Manifest();
    manifest
      .from('subscribers')
      .create({ email })
      .then(() => {
        form.reset();
        alert('Successfully subscribed!');
      })
      .catch((error) => {
        console.error('Error adding subscriber:', error);
        alert(`Failed to add subscriber: ${error.message || error}`);
      });
  };

  return (
    // ... Your existing code here>
  );
}
</htmlformelement>

Now, add the onSubmit={handleSubmit} attribute to your

tag:

Testing the form

Time to see our form in action! Enter an email address and hit submit. You should get a confirmation message.

Check the admin panel, and voilà! this email is now in the subscriber list!

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Enhancing user experience

Let’s add alerts to indicate whether the subscription was successful or not. We’ll use the ShadUI alert component.

Install the alert component with:

npx shadcn@latest add alert

We can now add the alert function, and integrate it into our form. Here is the final page.tsx page:

'use client'

import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import Manifest from '@mnfst/sdk'
import { useState } from 'react'

export default function Home() {
  const [alertVisible, setAlertVisible] = useState(false) // State to manage alert visibility
  const [alertMessage, setAlertMessage] = useState('') // Message to display in the alert

  const handleSubmit = (e: React.FormEvent<htmlformelement>) => {
    e.preventDefault()

    // Retrieve email from the input field
    const form = e.currentTarget as HTMLFormElement
    const emailInput = form.querySelector(
      'input[name="email"]'
    ) as HTMLInputElement
    const email = emailInput?.value

    if (!email) {
      setAlertMessage('Please enter a valid email.')
      setAlertVisible(true)
      setTimeout(() => setAlertVisible(false), 3000) // Hide the alert after 3 seconds
      return
    }

    const manifest = new Manifest()
    manifest
      .from('subscribers')
      .create({ email })
      .then(() => {
        form.reset() // Reset the email input field after success
        setAlertMessage(
          'Successfully subscribed! We will contact you if you are selected.'
        )
        setAlertVisible(true) // Show success alert
        setTimeout(() => setAlertVisible(false), 3000) // Hide the alert after 3 seconds
      })
      .catch((error) => {
        setAlertMessage(`Failed to add subscriber: ${error.message || error}`)
        setAlertVisible(true) // Show error alert
        setTimeout(() => setAlertVisible(false), 3000) // Hide the alert after 3 seconds
      })
  }

  return (
    <div classname="w-full lg:grid lg:grid-cols-5 min-h-screen flex sm:items-center sm:justify-center sm:grid">
      <div classname="flex items-center justify-center py-12 col-span-2 px-8">
        <div classname="relative mx-auto grid max-w-[540px] gap-6">
          <div classname="grid gap-2 text-left">
            <h1 classname="text-3xl font-bold">
              Subscribe to our Newsletter! ?
            </h1>
            <p classname="text-balance text-muted-foreground">
              Get the latest news, updates, and special offers delivered
              straight to your inbox.
            </p>
          </div>
          <form onsubmit="{handleSubmit}" classname="grid gap-4">
            <div classname="flex w-full max-w-sm items-center space-x-2">
              <input type="email" placeholder="m@example.com" name="email" required>
              <button type="submit">Subscribe</button>
            </div>
            <p classname="text-sm text-muted-foreground">
              Sent out weekly on Mondays. Always free.
            </p>
          </form>
          {/* Display the alert based on alertVisible state */}
          {alertVisible && (
            <alert classname="absolute bottom-[-90px] bg-teal-300 border-teal-400 text-teal-800">
              <alertdescription>{alertMessage}</alertdescription>
            </alert>
          )}
        </div>
      </div>
      <div classname="hidden bg-muted lg:block col-span-3 min-h-screen bg-gradient-to-t from-green-50 via-pink-100 to-purple-100"></div>
    </div>
  )
}
</htmlformelement>

Let's try the form with the alert by entering a new valid email.

How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

Congratulations! ? You’ve just built a fully functional newsletter subscription application in a flash! ⚡

Conclusion

By leveraging Manifest alongside your favorite frontend tools, you can rapidly create applications with minimal effort. Manifest has been instrumental in speeding up our development process, allowing us to set up a complete backend in just minutes.

I hope this guide was helpful and that you learned how to create a simple and effective newsletter subscription system for your future projects.

If you'd like to access the full project code, you can check out the repository here.

If you liked using Manifest, consider giving us a ⭐ on GitHub to support the project and stay updated!

The above is the detailed content of How to create a newsletter signup form in just minutes with shadcn/UI and Manifest. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.