Inputs & controlsstable

    Form

    A component for displaying forms.

    Follow the installation and quick start below to use Form in your project, or read the complete setup guide.

    Accessible by designLight & darkCopy. Customize. Ship.
    On this page
    Live previewFluid

    Create an account

    Interactive exampleReact / TypeScript / Tailwind CSS
    ADD TO YOUR PROJECT

    Installation

    1. Initialize once

    Run from an existing React project with Node.js 18 or later. Skip this step if the project already has u-lib.json. Initialization copies the shared stylesheet and adds its import to your application entry.

    npx @scriptwithahmad/u-lib@0.2.2 init

    2. Add Form and example components

    This command includes the UI components used by this page's usage examples. The CLI copies editable source into your components directory and installs each component's dependencies. Existing source files are preserved.

    npx @scriptwithahmad/u-lib@0.2.2 add form card checkbox button input label select

    Choose the tab for your package manager. Yarn commands require modern Yarn; Yarn Classic users can use npx. Use --dry-run to preview changes. See the installation guide for custom paths, JavaScript output and package-import alternatives.

    USE IN YOUR APP

    Quick start

    Copy this example into src/Example.tsx (or Example.tsx at the project root when you do not use src). Imports assume the default CLI paths. From a nested file such as src/app/page.tsx, adjust ./components to ../components. Keep the client directive in Next.js when using state or event handlers.

    form-example.tsx
    "use client";
    import { Card } from "./components/ui/card";
    import { useId, useState } from "react";
    import { Checkbox } from "./components/ui/checkbox";
    import { Button } from "./components/ui/button";
    import { Input } from "./components/ui/input";
    import { Label } from "./components/ui/label";
    import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./components/ui/select";
    export default function RenderForm() {
      const id = useId();
      const [password, setPassword] = useState("");
      const [country, setCountry] = useState("pk");
      const [terms, setTerms] = useState(false);
      const [submitted, setSubmitted] = useState(false);
      const [errors, setErrors] = useState<Record<string, string>>({});
      function fieldError(input: HTMLInputElement) {
        if (!input.value.trim()) return input.name === "password" ? "Enter a password." : input.name === "email" ? "Enter your email address." : "Enter your name.";
        if (input.name === "email" && input.validity.typeMismatch) return "Enter a valid email address.";
        if (input.name === "password" && input.value.length < 8) return "Use at least 8 characters.";
        return "";
      }
      function updateField(input: HTMLInputElement) {
        setSubmitted(false);
        setErrors(previous => previous[input.name] ? { ...previous, [input.name]: fieldError(input) } : previous);
      }
      return <Card asChild><form noValidate className="w-full max-w-md space-y-4 p-6"
        onSubmit={(event) => {
          event.preventDefault();
          const form = event.currentTarget;
          const next: Record<string, string> = {};
          for (const name of ["name", "email", "password"]) {
            const input = form.elements.namedItem(name) as HTMLInputElement;
            const message = fieldError(input);
            if (message) next[name] = message;
          }
          if (!terms) next.terms = "Accept the terms and conditions to continue.";
          setErrors(next);
          setSubmitted(Object.keys(next).length === 0);
          const first = Object.keys(next)[0];
          if (first === "terms") form.querySelector<HTMLButtonElement>('[role="checkbox"]')?.focus();
          else if (first) (form.elements.namedItem(first) as HTMLInputElement)?.focus();
        }}
        onReset={() => { setPassword(""); setCountry("pk"); setTerms(false); setSubmitted(false); setErrors({}); }}>
        <h2 className="text-xl font-semibold">Create an account</h2>
        <div className="space-y-2"><Label htmlFor={`${id}-name`}>Name</Label><Input id={`${id}-name`} name="name" placeholder="Your name" autoComplete="name" required aria-invalid={Boolean(errors.name)} aria-describedby={errors.name ? `${id}-name-error` : undefined} onChange={event => updateField(event.target)} />{errors.name && <p id={`${id}-name-error`} className="text-xs text-destructive-text">{errors.name}</p>}</div>
        <div className="space-y-2"><Label htmlFor={`${id}-email`}>Email</Label><Input id={`${id}-email`} name="email" type="email" placeholder="you@example.com" autoComplete="email" required aria-invalid={Boolean(errors.email)} aria-describedby={errors.email ? `${id}-email-error` : undefined} onChange={event => updateField(event.target)} />{errors.email && <p id={`${id}-email-error`} className="text-xs text-destructive-text">{errors.email}</p>}</div>
        <div className="space-y-2"><Label htmlFor={`${id}-password`}>Password</Label>
          <Input id={`${id}-password`} name="password" type="password" autoComplete="new-password" minLength={8} required value={password} onChange={(event) => { setPassword(event.target.value); updateField(event.target); }} aria-invalid={Boolean(errors.password)} aria-describedby={errors.password ? `${id}-password-error` : undefined} />
          {errors.password && <p id={`${id}-password-error`} className="text-xs text-destructive-text">{errors.password}</p>}
        </div>
        <div className="space-y-2"><Label htmlFor={`${id}-country`}>Country</Label>
          <Select name="country" value={country} onValueChange={(value) => { setCountry(value); setSubmitted(false); }}><SelectTrigger id={`${id}-country`} className="h-10 rounded-2xl bg-muted/60 px-4"><SelectValue /></SelectTrigger><SelectContent align="start" sideOffset={8} collisionPadding={16} className="max-h-[var(--radix-select-content-available-height)] max-w-[calc(100vw-32px)] rounded-[26px] p-1 shadow-[0_2px_3px_#00000008,0_14px_32px_#00000018] [&_[role=option]]:min-h-9 [&_[role=option]]:rounded-[18px] [&_[role=option]]:pl-4 [&_[role=option]]:pr-10 [&_[role=option]]:py-2 [&_[role=option]]:text-[13px] [&_[role=option]>span:first-child]:right-4">
            <SelectItem value="pk">Pakistan</SelectItem><SelectItem value="us">United States</SelectItem><SelectItem value="ca">Canada</SelectItem><SelectItem value="au">Australia</SelectItem><SelectItem value="fr">France</SelectItem><SelectItem value="de">Germany</SelectItem>
          </SelectContent></Select>
        </div>
        <div className="flex items-center gap-2"><Checkbox id={`${id}-terms`} required checked={terms} aria-invalid={Boolean(errors.terms)} aria-describedby={errors.terms ? `${id}-terms-error` : undefined} onCheckedChange={(checked) => { setTerms(checked === true); setSubmitted(false); setErrors(previous => ({ ...previous, terms: checked === true ? "" : previous.terms })); }} /><Label htmlFor={`${id}-terms`}>I agree to the terms and conditions</Label></div>
        {errors.terms && <p id={`${id}-terms-error`} className="text-xs text-destructive-text">{errors.terms}</p>}
        {Object.values(errors).some(Boolean) && <p role="alert" className="text-xs text-destructive-text">Please correct the highlighted fields.</p>}
        <div className="flex gap-3"><Button type="submit">Submit</Button><Button type="reset" variant="outline">Reset</Button></div>
        {submitted && <p role="status" className="text-sm">Demo submitted successfully. No account was created.</p>}
      </form></Card>;
    }

    The first example is an application form composed from controls. For the Form helpers in the API reference, use React Hook Form with Form/FormProvider, FormField and FormItem before rendering FormLabel, FormControl or FormMessage.

    Keep the shared stylesheet imported once. Replace sample image URLs and data with your own. Examples may use layout utilities beyond the precompiled component styles; compile added Tailwind classes in your app or replace them with your own CSS. Customize local source or className, and preserve accessible names and keyboard behavior.

    BUILD WITH IT

    Usage examples

    1 examples

    Try each example, then switch to Code to copy its complete implementation. These catalog snippets use the website's @/components/ui alias; replace it with your local generated path as shown in Quick start.

    01

    Basic Usage

    A complete form example. Copy this into a client component.

    Basic Usage

    Loading example…

    THE API

    Props & configuration

    Reference

    Everything you need to fine-tune this component.

    Props and configuration
    PropTypeDefaultDescription
    onSubmitFormEventHandler<HTMLFormElement>—Handle submission on the native form element.
    onResetFormEventHandler<HTMLFormElement>—Reset controlled field state with native form fields.