首页 web前端 js教程 如何使用 shadcn/UI 和 Manifest 在几分钟内创建新闻通讯注册表单

如何使用 shadcn/UI 和 Manifest 在几分钟内创建新闻通讯注册表单

Oct 09, 2024 am 06:19 AM

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 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>
  );
}
登录后复制

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:

<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>
登录后复制

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>
  );
}
登录后复制

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

<form onSubmit={handleSubmit} className="grid gap-4">
登录后复制

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) => {
    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} )}
) }
登录后复制

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

热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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1670
14
CakePHP 教程
1428
52
Laravel 教程
1329
25
PHP教程
1274
29
C# 教程
1256
24
Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C到JavaScript:所有工作方式 从C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在行动中:现实世界中的示例和项目 JavaScript在行动中:现实世界中的示例和项目 Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

了解JavaScript引擎:实施详细信息 了解JavaScript引擎:实施详细信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:社区,图书馆和资源 Python vs. JavaScript:社区,图书馆和资源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python vs. JavaScript:开发环境和工具 Python vs. JavaScript:开发环境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

C/C在JavaScript口译员和编译器中的作用 C/C在JavaScript口译员和编译器中的作用 Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

See all articles