shadcn-form-builder

repository·main·Indexed 25 days ago

https://github.com/hasanharman/form-builder

A dynamic tool for creating, customizing, and validating forms in web applications, built with React, Next.js, Tailwind CSS, and ShadCN components. It features a builder interface for adding and configuring inputs, real-time validation using Zod, and utilities for generating JSON Schemas from form fields. The library includes core components like FormContainer, InputField, and SelectField, as well as a specialized CreditCard component.

Tokens
6.2K
Snippets
12
Records
52
Agent score
83%

What's inside shadcn-form-builder

  1. Create a form using the builder interface

    main

    Follow these steps to build a form within the application interface:

    1. Access the Builder: Navigate to the form builder interface in your running application.
    2. Add Inputs: Use the provided toolbar to add various input types.
    3. Customize Inputs: Select an input field to configure its properties, such as label, placeholder, and required validation.
    4. Save & Preview: Save your progress and preview the resulting form.
  2. Use the CreditCard component

    main

    The CreditCard component is a controlled component. You must manage the card data in your own state and pass it to the value prop, while using the onChange prop to update your state when the user interacts with the card.

    import { useState } from 'react'
    import { CreditCard } from '@/components/ui/credit-card'
    
    function PaymentForm() {
      const [creditCard, setCreditCard] = useState({
        cardholderName: '',
        cardNumber: '',
        expiryMonth: '',
        expiryYear: '',
        cvv: '',
        cvvLabel: 'CVC' as const
      })
    
      return (
        <CreditCard
          value={creditCard}
          onChange={setCreditCard}
        />
      )
    }
  3. Implement CreditCard with form validation

    main

    To use the CreditCard component within a form, validate the fields in your state to enable or disable submission buttons.

    import { useState } from 'react'
    import { CreditCard } from '@/components/ui/credit-card'
    import { Button } from '@/components/ui/button'
    
    export default function CheckoutForm() {
      const [cardData, setCardData] = useState({
        cardholderName: '',
        cardNumber: '',
        expiryMonth: '',
        expiryYear: '',
        cvv: '',
        cvvLabel: 'CVC' as const
      })
    
      const isValid = cardData.cardholderName.trim() && 
                      cardData.cardNumber.trim() && 
                      cardData.expiryMonth.trim() && 
                      cardData.expiryYear.trim() && 
                      cardData.cvv.trim()
    
      const handleSubmit = () => {
        if (isValid) {
          console.log('Processing payment...', cardData)
        }
      }
    
      return (
        <div className="max-w-md mx-auto p-6 space-y-6">
          <CreditCard
            value={cardData}
            onChange={setCardData}
          />
          <Button 
            onClick={handleSubmit} 
            disabled={!isValid}
            className="w-full"
          >
            Process Payment
          </Button>
        </div
      )
    }
  4. Handle form submission

    main

    To process form data, send a POST request to your submission endpoint (e.g., /api/form-submit) with the form data serialized as JSON.

    const handleSubmit = async (data) => {
      try {
        const response = await fetch('/api/form-submit', {
          method: 'POST',
          body: JSON.stringify(data),
          headers: {
            'Content-Type': 'application/json',
          },
        });
        const result = await response.json();
        console.log('Form submitted successfully:', result);
      } catch (error) {
        console.error('Error submitting form:', error);
      }
    };
  5. Validate forms with Zod

    main

    Form Builder uses Zod for real-time input validation. You can define a schema to enforce rules like required fields, minimum lengths, or specific formats (e.g., email).

    import { z } from 'zod';
    
    const formSchema = z.object({
      name: z.string().min(1, "Name is required"),
      email: z.string().email("Invalid email address"),
      age: z.number().min(18, "You must be at least 18 years old"),
    });
  6. Configure site settings via siteConfig

    main

    The siteConfig object is used to manage global site metadata, social links, and FAQ content. You can customize the site name, description, URL, and SEO keywords. The url property defaults to http://localhost:3000 unless the NEXT_PUBLIC_APP_URL environment variable is provided.

    export const siteConfig = {
      name: 'acme.ai',
      description: 'Automate your workflow with AI',
      url: process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000',
      keywords: ['SaaS', 'Template', 'Next.js', 'React', 'Tailwind CSS'],
      links: {
        email: 'support@acme.ai',
        twitter: 'https://twitter.com/magicuidesign',
        discord: 'https://discord.gg/87p2vpsat5',
        github: 'https://github.com/magicuidesign/magicui',
        instagram: 'https://instagram.com/magicuidesign/',
      },
      faqs: [
        {
          question: 'What is this tool for?',
          answer: <span>...</span>,
        },
        // ...
      ],
    }
  7. Configure next-sitemap settings

    main

    The next-sitemap.config.js file is used to configure the next-sitemap package. It accepts an object of type IConfig. The primary configuration keys are siteUrl and generateRobotsTxt.

    /** @type {import('next-sitemap').IConfig} */
    module.exports = {
      siteUrl: process.env.SITE_URL || 'https://www.shadcn-form.com',
      generateRobotsTxt: true, // (optional)
      // ...other options
    }
  8. Reference CreditCardProps and CreditCardValue

    main

    The CreditCard component accepts the following props and data structures.

    interface CreditCardValue {
      cardholderName: string
      cardNumber: string
      expiryMonth: string
      expiryYear: string
      cvv: string
      cvvLabel: 'CCV' | 'CVC'
    }
    
    interface CreditCardProps {
      value?: CreditCardValue
      onChange?: (value: CreditCardValue) => void
      className?: string
    }
  9. Form Builder core components

    main

    The library provides several reusable components for building forms:

    • FormContainer: The main container for all form elements.
    • InputField: A customizable input component.
    • SelectField: A dropdown selection component.
    • CheckboxField: A checkbox input component.
    • Button: A styled button component used for form submission.