搜尋
首頁web前端js教程如何使用 shadcn/UI 和 Manifest 在幾分鐘內建立電子報註冊表單

In today’s digital world, being able to quickly test your ideas and interact with your users is crucial, whether you’re building an MVP, launching a startup, or delivering a project on a tight deadline. Creating a newsletter subscription form is often necessary to validate your concept, engage early users, build a community of interested people, and gather feedback.

Turnkey solutions can be costly, while using free tools is still complex and time-consuming.

In this tutorial, I’ll show you how to create a newsletter subscription form in less than 20 minutes. No complex configurations, no headaches. Just a form with a fully functional subscription system!

Stack Used

  • shadcn/UI: ready-to-use, beautifully designed components to build the frontend.
  • Manifest: The fastest and easiest way to build a complete backend, just by filling a YAML file.

By the end of this tutorial, you’ll have a fully operational form to collect your first subscribers. Ready? Let’s go!

What is Manifest?

Manifest is our open-source Backend-as-a-Service (BaaS). It allows to create a complete backend for your application.

By simply filling in a single YAML file, you generate a backend with a database, an API, and a user-friendly admin panel for non-technical administrators.

This allows you to focus on building your product instead of dealing with backend complexity.

As of today, we’ve just released our MVP, and we’re counting on community feedback to help us evolve the product in the right direction.

Manifest is available on GitHub, so feel free to give it a ⭐ if you like the project!

Planning the interface

Our goal is a single screen displaying a subscription field and notification messages. It's simple, effective, and functional. Here’s what we’ll get:

  • The frontend for subscribers
  • The admin panel for the administrators

Creating the frontend with shadcn/UI

We’ll start by creating the project with the frontend, i.e., the visual part of our newsletter subscription form.

I chose to use shadcn/UI with Next.js. Run the following command in your terminal:

npx shadcn@latest init -d

You’ll be prompted to start a new Next.js project and name your project. Answer “Y” and call it newsletter-form.

Once the project is created, you should have your frontend ready, with these files:

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

Start the development server by running: npm run dev.

Click on the provided link in the terminal. It should open the NextJS welcome screen in your default web browser at https://localhost:3000.

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

Creating the static form

Let’s create our form by editing app/page.tsx. Since shadcn works with TailwindCSS, we’ll use its classes to build the desired interface. Copy the following 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>
  );
}

You should see a split screen with an area for the form on the left and a gradient space on the right.

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

Now let’s add the form. It will include the following shadcn components:

  • Input
  • Button

Install these components via your terminal with the following commands:

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

Then import the components in your page.tsx file like this:

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

Use these two components by adding the following snippet inside the existing

tag:

Sent out weekly on Mondays. Always free.

You should have a responsive newsletter form on your frontend. Take a moment to admire your work. And relax, our 20-minute promise is still intact!

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

Creating the backend with Manifest

Let’s add the backend to store the subscribers and allow administrators to manage them via an admin panel.

Install Manifest at the root of the project with the following command:

npx add-manifest

Once the backend is installed, you should see the following files in your repository:

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!

以上是如何使用 shadcn/UI 和 Manifest 在幾分鐘內建立電子報註冊表單的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /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:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中