Home Web Front-end JS Tutorial How to create a newsletter signup form in just minutes with shadcn/UI and Manifest

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

Oct 09, 2024 am 06:19 AM

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
Copy after login

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 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 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>
  );
}
Copy after login

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
Copy after login

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

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

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

<form className="grid gap-4">
  <div className="flex w-full max-w-sm items-center space-x-2">
    <Input type="email" placeholder="Email" name="email" />
    <Button type="submit">Subscribe</Button>
  </div>
  <p className="text-sm text-muted-foreground">
    Sent out weekly on Mondays. Always free.
  </p>
</form>
Copy after login

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
Copy after login

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 }
Copy after login

Run the following command to start your server:

npm run manifest
Copy after login

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
Copy after login

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';
Copy after login

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>
  );
}
Copy after login

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

tag:

<form onSubmit={handleSubmit} className="grid gap-4">
Copy after login

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
Copy after login

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) => {
    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 (
    

Subscribe to our Newsletter! ?

Get the latest news, updates, and special offers delivered straight to your inbox.

<form onSubmit={handleSubmit} className="grid gap-4">

Sent out weekly on Mondays. Always free.

{/* Display the alert based on alertVisible state */} {alertVisible && ( {alertMessage} )}
) }
Copy after login

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles