Field
Accessible React form fields built on shadcn/ui: Field, FieldLabel, FieldDescription, FieldError, FieldSet and FieldGroup lay out labels, hints and validation errors for any input, with invalid and disabled states, horizontal and responsive layouts and selectable choice cards — plus Motion blocks for errors that grow open, fields that shake on a failed submit and a complete sign-up form validated without a form library.
- Drop-in shadcn API
- Works with any validation library
- Choice cards
- Responsive layout
- Motion blocks
"use client";
import { SignupForm } from "@/components/dusk/field/signup-form";
export default function SignupFormDemo() {
return (
<div className="w-full max-w-sm">
<SignupForm onSubmit={() => new Promise<void>((resolve) => setTimeout(resolve, 1200))} />
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/field.json1. Install the dependencies.
npm install class-variance-authority @radix-ui/react-label2. Copy the source into
components/ui/field.tsx.field.tsx "use client"; import * as React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { Label } from "@/components/ui/label"; import { cn } from "@/lib/utils"; /** * DuskUI Field — a drop-in upgrade of the shadcn/ui Field. * * Same parts, props and data-slot attributes as shadcn (Field, FieldLabel, * FieldDescription, FieldError, FieldGroup, FieldSet, FieldLegend, * FieldSeparator, FieldContent, FieldTitle) plus: * - `data-invalid` on a Field eases the label to red; the description stays * readable instead of turning red too. * - `data-disabled` dims the label and description together. * - FieldError fades and slides in when it mounts, and accepts the * `errors` array from any validation library (deduplicated by message). * - Choice cards (a FieldLabel wrapping a horizontal Field) get a subtle * hover background and a mint border when their checkbox, radio or switch is on. * - `orientation`: vertical, horizontal or responsive (switches to a row * once the FieldGroup is wider than 28rem, via a container query). * CSS only — no animation library. Pair it with the Animated Field Error * block for height animations and a shake on submit. */ /** A `<fieldset>` that groups related fields, e.g. an address or a set of checkboxes. */ function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) { return ( <fieldset data-slot="field-set" className={cn( "flex min-w-0 flex-col gap-6", "has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", "disabled:opacity-60", className )} {...props} /> ); } /** The fieldset caption. `variant="label"` makes it the size of a field label. */ function FieldLegend({ className, variant = "legend", ...props }: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) { return ( <legend data-slot="field-legend" data-variant={variant} className={cn("mb-3 font-medium", "data-[variant=legend]:text-base", "data-[variant=label]:text-sm", className)} {...props} /> ); } /** Stacks fields with consistent spacing. Also the container for `orientation="responsive"`. */ function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="field-group" className={cn( "group/field-group @container/field-group flex w-full flex-col gap-7", "data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4", className )} {...props} /> ); } const fieldVariants = cva("group/field flex w-full gap-3", { variants: { orientation: { vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"], horizontal: [ "flex-row items-center", "[&>[data-slot=field-label]]:flex-auto", "has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", ], responsive: [ "flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto", "@md/field-group:[&>[data-slot=field-label]]:flex-auto", "@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", ], }, }, defaultVariants: { orientation: "vertical" }, }); /** * One form control with its label, description and error. Set * `data-invalid` / `data-disabled` to style the whole field. */ function Field({ className, orientation = "vertical", ...props }: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) { return ( <div role="group" data-slot="field" data-orientation={orientation} className={cn(fieldVariants({ orientation }), className)} {...props} /> ); } /** Wraps a label and description next to a checkbox, radio or switch in a horizontal Field. */ function FieldContent({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="field-content" className={cn("group/field-content flex flex-1 flex-col gap-1.5 leading-snug", className)} {...props} /> ); } /** A Label wired for fields. Wrap a whole horizontal Field in it to make a selectable choice card. */ function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>) { return ( <Label data-slot="field-label" className={cn( "group/field-label peer/field-label flex w-fit gap-2 leading-snug", "group-data-[disabled=true]/field:opacity-50 group-data-[invalid=true]/field:text-destructive", // Choice card: a label that wraps a Field. "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4", "has-[>[data-slot=field]]:cursor-pointer has-[>[data-slot=field]]:transition-[border-color,background-color,box-shadow] has-[>[data-slot=field]]:duration-150 has-[>[data-slot=field]]:hover:bg-accent/40", "has-data-[state=checked]:border-primary has-data-[state=checked]:bg-primary/5", "has-focus-visible:has-[>[data-slot=field]]:ring-[3px] has-focus-visible:has-[>[data-slot=field]]:ring-ring/50", className )} {...props} /> ); } /** A label-styled heading for fields that don't have a single control to label (use inside FieldContent). */ function FieldTitle({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="field-label" className={cn( "flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50", className )} {...props} /> ); } /** Helper text. Link it to the control with `id` + `aria-describedby`. */ function FieldDescription({ className, ...props }: React.ComponentProps<"p">) { return ( <p data-slot="field-description" className={cn( "text-sm leading-normal font-normal text-muted-foreground group-has-[[data-orientation=horizontal]]/field:text-balance", "transition-opacity duration-200 group-data-[disabled=true]/field:opacity-50", "last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5", "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-foreground", className )} {...props} /> ); } /** A divider between field groups, with optional centered text (e.g. "Or continue with"). */ function FieldSeparator({ children, className, ...props }: React.ComponentProps<"div"> & { children?: React.ReactNode }) { return ( <div data-slot="field-separator" data-content={!!children} className={cn("relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2", className)} {...props} > <div aria-hidden className="absolute inset-x-0 top-1/2 h-px bg-border" /> {children && ( <span data-slot="field-separator-content" className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground" > {children} </span> )} </div> ); } /** * The field's error message. Renders nothing when empty. Pass `children`, or * the `errors` array from a validation library (`{ message?: string }[]`). * Link it to the control with `id` + `aria-describedby`. */ function FieldError({ className, children, errors, ...props }: React.ComponentProps<"div"> & { errors?: Array<{ message?: string } | undefined> }) { const content = React.useMemo(() => { if (children) return children; if (!errors?.length) return null; const unique = [...new Map(errors.map((error) => [error?.message, error])).values()].filter( (error) => error?.message ); if (unique.length === 0) return null; if (unique.length === 1) return unique[0]?.message; return ( <ul className="ml-4 flex list-disc flex-col gap-1"> {unique.map((error, index) => ( <li key={index}>{error?.message}</li> ))} </ul> ); }, [children, errors]); if (!content) return null; return ( <div role="alert" data-slot="field-error" className={cn( "text-sm font-normal text-destructive", "animate-in fade-in-0 slide-in-from-top-1 duration-200 ease-out motion-reduce:slide-in-from-top-0", className )} {...props} > {content} </div> ); } export { Field, FieldLabel, FieldDescription, FieldError, FieldGroup, FieldLegend, FieldSeparator, FieldSet, FieldContent, FieldTitle, };
Adds components/ui/field.tsx and the DuskUI components/ui/label.tsx it builds on. Same parts and data-slot attributes as shadcn/ui, so existing forms keep working.
Usage
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
export function UsernameField({ error }: { error?: string }) {
return (
<Field data-invalid={!!error || undefined}>
<FieldLabel htmlFor="username">Username</FieldLabel>
<Input
id="username"
aria-invalid={!!error || undefined}
aria-describedby="username-hint username-error"
/>
<FieldDescription id="username-hint">Your public handle.</FieldDescription>
<FieldError id="username-error">{error}</FieldError>
</Field>
)
}Examples
Label, description & error
data-invalid eases the label to red while the hint stays readable; data-disabled dims label and hint together. FieldError renders nothing when empty and fades in when it appears.
Your public handle. You can change it later.
Managed by your organization.
import { Field, FieldDescription, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
export default function FieldBasicDemo() {
return (
<FieldGroup className="w-full max-w-sm gap-6">
<Field>
<FieldLabel htmlFor="field-username">Username</FieldLabel>
<Input id="field-username" placeholder="dusk.dev" aria-describedby="field-username-hint" />
<FieldDescription id="field-username-hint">Your public handle. You can change it later.</FieldDescription>
</Field>
<Field data-invalid>
<FieldLabel htmlFor="field-site">Website</FieldLabel>
<Input id="field-site" defaultValue="not a url" aria-invalid aria-describedby="field-site-error" />
<FieldError id="field-site-error">Enter a full URL, like https://example.com.</FieldError>
</Field>
<Field data-disabled>
<FieldLabel htmlFor="field-team">Team</FieldLabel>
<Input id="field-team" defaultValue="Acme Inc." disabled aria-describedby="field-team-hint" />
<FieldDescription id="field-team-hint">Managed by your organization.</FieldDescription>
</Field>
</FieldGroup>
);
}Fieldset, separator & orientation
Group related controls in a FieldSet with a FieldLegend. Use orientation="horizontal" for checkboxes and switches, and "responsive" to switch from stacked to a row once the FieldGroup is wide enough (a container query, not a viewport breakpoint).
Pause notifications from 10pm to 8am.
Row on wide screens, stacked on narrow ones.
import { Checkbox } from "@/components/ui/checkbox";
import {
Field,
FieldContent,
FieldDescription,
FieldGroup,
FieldLabel,
FieldLegend,
FieldSeparator,
FieldSet,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
const channels = [
{ id: "notify-mentions", label: "Mentions", defaultChecked: true },
{ id: "notify-replies", label: "Replies to my threads", defaultChecked: true },
{ id: "notify-digest", label: "Weekly digest", defaultChecked: false },
];
export default function FieldFieldsetDemo() {
return (
<FieldGroup className="w-full max-w-md">
<FieldSet>
<FieldLegend>Notifications</FieldLegend>
<FieldDescription>Choose what lands in your inbox.</FieldDescription>
<FieldGroup data-slot="checkbox-group" className="gap-3">
{channels.map((channel) => (
<Field key={channel.id} orientation="horizontal">
<Checkbox id={channel.id} defaultChecked={channel.defaultChecked} />
<FieldLabel htmlFor={channel.id} className="font-normal">
{channel.label}
</FieldLabel>
</Field>
))}
</FieldGroup>
</FieldSet>
<FieldSeparator />
<Field orientation="horizontal">
<FieldContent>
<FieldLabel htmlFor="notify-quiet">Quiet hours</FieldLabel>
<FieldDescription id="notify-quiet-hint">Pause notifications from 10pm to 8am.</FieldDescription>
</FieldContent>
<Switch id="notify-quiet" aria-describedby="notify-quiet-hint" />
</Field>
<Field orientation="responsive">
<FieldContent>
<FieldLabel htmlFor="notify-email">Forward to</FieldLabel>
<FieldDescription id="notify-email-hint">Row on wide screens, stacked on narrow ones.</FieldDescription>
</FieldContent>
<Input id="notify-email" type="email" placeholder="you@example.com" aria-describedby="notify-email-hint" className="@md/field-group:max-w-52" />
</Field>
</FieldGroup>
);
}Choice cards
Wrap a horizontal Field in a FieldLabel and the whole card becomes the hit area. Its border turns mint while its switch or checkbox is on.
import { Checkbox } from "@/components/ui/checkbox";
import { Field, FieldContent, FieldDescription, FieldLabel, FieldSet, FieldLegend, FieldTitle } from "@/components/ui/field";
import { Switch } from "@/components/ui/switch";
export default function FieldChoiceCardDemo() {
return (
<FieldSet className="w-full max-w-sm gap-3">
<FieldLegend variant="label">Workspace features</FieldLegend>
<FieldLabel htmlFor="feature-ai">
<Field orientation="horizontal">
<FieldContent>
<FieldTitle>AI summaries</FieldTitle>
<FieldDescription>Summarize long threads in one click.</FieldDescription>
</FieldContent>
<Switch id="feature-ai" defaultChecked />
</Field>
</FieldLabel>
<FieldLabel htmlFor="feature-analytics">
<Field orientation="horizontal">
<Checkbox id="feature-analytics" />
<FieldContent>
<FieldTitle>Usage analytics</FieldTitle>
<FieldDescription>Weekly charts of who uses what.</FieldDescription>
</FieldContent>
</Field>
</FieldLabel>
</FieldSet>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Field Error
AnimatedFieldError grows open and collapses shut so the form below glides, and cross-fades when the message changes. AnimatedField shakes once whenever its shakeKey changes while invalid — pass your submit counter. Submit the demo empty, then with a non-work email.
"use client";
import * as React from "react";
import { AnimatedField, AnimatedFieldError } from "@/components/dusk/field/animated-field-error";
import { Button } from "@/components/ui/button";
import { FieldDescription, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
function check(value: string) {
if (!value.trim()) return "Enter an email address.";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) return "That email doesn't look right.";
if (!value.trim().endsWith("@dusk.dev")) return "Use your @dusk.dev work email.";
return undefined;
}
export default function AnimatedFieldErrorDemo() {
const [email, setEmail] = React.useState("");
const [submitted, setSubmitted] = React.useState(0);
const [done, setDone] = React.useState(false);
const error = submitted > 0 ? check(email) : undefined;
return (
<form
noValidate
className="grid w-full max-w-sm gap-4"
onSubmit={(event) => {
event.preventDefault();
setSubmitted((n) => n + 1);
setDone(!check(email));
}}
>
<AnimatedField invalid={!!error} shakeKey={submitted}>
<FieldLabel htmlFor="invite-email">Work email</FieldLabel>
<Input
id="invite-email"
type="email"
placeholder="ada@dusk.dev"
value={email}
onChange={(event) => {
setEmail(event.target.value);
setDone(false);
}}
aria-invalid={!!error || undefined}
aria-describedby={error ? "invite-email-hint invite-email-error" : "invite-email-hint"}
/>
<FieldDescription id="invite-email-hint">We'll send the invite here.</FieldDescription>
<AnimatedFieldError id="invite-email-error">{error}</AnimatedFieldError>
</AnimatedField>
<Button type="submit">{done ? "Invite sent" : "Send invite"}</Button>
</form>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-field-error.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/field/animated-field-error.tsx.animated-field-error.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useAnimate, useReducedMotion, type Transition } from "motion/react"; import { Field } from "@/components/ui/field"; import { cn } from "@/lib/utils"; const heightSpring: Transition = { type: "spring", duration: 0.32, bounce: 0 }; const swapSpring: Transition = { type: "spring", duration: 0.28, bounce: 0 }; export interface AnimatedFieldProps extends React.ComponentProps<typeof Field> { /** Marks the field invalid (sets `data-invalid`). */ invalid?: boolean; /** * Change this value — e.g. a submit counter — to shake the field once. * It only shakes while `invalid` is true, and never on the first render. */ shakeKey?: number | string; } /** * A Field that shakes once when `shakeKey` changes while it's invalid — the * classic "nope" after a failed submit. The shake is a short decaying * translate, so nothing around it reflows. Skipped under reduced motion. */ export function AnimatedField({ invalid = false, shakeKey, className, ...props }: AnimatedFieldProps) { const [scope, animate] = useAnimate<HTMLDivElement>(); const reduceMotion = useReducedMotion() ?? false; const lastKey = React.useRef(shakeKey); React.useEffect(() => { if (lastKey.current === shakeKey) return; lastKey.current = shakeKey; if (!invalid || reduceMotion || !scope.current) return; animate(scope.current, { x: [0, -8, 7, -5, 3, -1, 0] }, { duration: 0.45, ease: "easeOut" }); }, [shakeKey, invalid, reduceMotion, animate, scope]); return ( <Field ref={scope} data-invalid={invalid || undefined} className={cn("will-change-transform", className)} {...props} /> ); } export interface AnimatedFieldErrorProps { /** Put this id in the control's `aria-describedby`. */ id?: string; /** The message. Falsy hides the error. */ children?: React.ReactNode; /** * Classes for the collapsing wrapper. It carries `-mt-3` to cancel the * Field's `gap-3` while collapsed; change it if your Field uses another gap. */ className?: string; } /** * A field error that grows open and collapses shut (height + opacity) so the * form below glides instead of jumping. When the message changes it * cross-fades in place. The last message stays visible while collapsing, and * the element is a live `role="alert"`, so each new message is announced. * Under reduced motion it fades without moving. */ export function AnimatedFieldError({ id, children, className }: AnimatedFieldErrorProps) { const reduceMotion = useReducedMotion() ?? false; const hasError = Boolean(children); // Keep the last message so it can collapse with its text instead of blanking first. const [shown, setShown] = React.useState<React.ReactNode>(children); if (hasError && children !== shown) setShown(children); const swapKey = typeof shown === "string" || typeof shown === "number" ? String(shown) : "message"; return ( <AnimatePresence initial={false}> {hasError && ( <motion.div key="field-error" initial={{ height: 0, opacity: 0 }} animate={{ height: "auto", opacity: 1 }} exit={{ height: 0, opacity: 0 }} transition={reduceMotion ? { duration: 0.15 } : heightSpring} className={cn("-mt-3 overflow-hidden", className)} > <div id={id} role="alert" data-slot="field-error" className="grid pt-2 text-sm text-destructive"> <AnimatePresence initial={false} mode="popLayout"> <motion.span key={swapKey} className="[grid-area:1/1]" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -4 }} animate={{ opacity: 1, y: 0 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 4 }} transition={swapSpring} > {shown} </motion.span> </AnimatePresence> </div> </motion.div> )} </AnimatePresence> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| AnimatedField invalid | boolean | false | Sets data-invalid on the Field. |
| AnimatedField shakeKey | number | string | — | Change it (e.g. a submit count) to shake once while invalid. Never shakes on mount. |
| AnimatedFieldError id | string | — | Reference it from the control's aria-describedby. |
| AnimatedFieldError children | ReactNode | — | The message. Falsy collapses the error. |
| AnimatedFieldError className | string | "-mt-3" | Wrapper classes. The negative margin cancels the Field's gap-3 while collapsed. |
Sign-up Form
A complete form validated with plain React state: quiet until the first submit, then every invalid field shakes, focus jumps to the first problem and errors re-validate as you type. A successful submit swaps in a confirmation. validateSignup is exported — replace it with Zod or Valibot if you prefer.
"use client";
import { SignupForm } from "@/components/dusk/field/signup-form";
export default function SignupFormDemo() {
return (
<div className="w-full max-w-sm">
<SignupForm onSubmit={() => new Promise<void>((resolve) => setTimeout(resolve, 1200))} />
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/signup-form.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/field/signup-form.tsx.signup-form.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { CheckIcon } from "lucide-react"; import { AnimatedField, AnimatedFieldError } from "@/components/dusk/field/animated-field-error"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { FieldContent, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { cn } from "@/lib/utils"; export interface SignupValues { name: string; email: string; password: string; terms: boolean; } type FieldName = keyof SignupValues; type Errors = Partial<Record<FieldName, string>>; /** Dependency-free validation. Swap in Zod / Valibot and map their issues to the same shape. */ export function validateSignup(values: SignupValues): Errors { const errors: Errors = {}; if (!values.name.trim()) errors.name = "Tell us what to call you."; if (!values.email.trim()) errors.email = "Enter your email address."; else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) errors.email = "That email doesn't look right."; if (!values.password) errors.password = "Choose a password."; else if (values.password.length < 8) errors.password = `Use at least 8 characters (${8 - values.password.length} more).`; if (!values.terms) errors.terms = "Please accept the terms to continue."; return errors; } const order: FieldName[] = ["name", "email", "password", "terms"]; export interface SignupFormProps extends Omit<React.ComponentProps<"form">, "onSubmit"> { /** Called with valid values. Return a promise to show the loading state until it settles. */ onSubmit?: (values: SignupValues) => void | Promise<void>; /** Text on the submit button. */ submitLabel?: string; } /** * A sign-up form that validates without a form library. Nothing is flagged * while you type the first time; on submit every invalid field shakes, its * error grows open and focus jumps to the first problem. After that, fields * re-validate as you type, so errors collapse the moment they're fixed. * A successful submit swaps the form for a confirmation. */ export function SignupForm({ onSubmit, submitLabel = "Create account", className, ...props }: SignupFormProps) { const id = React.useId(); const reduceMotion = useReducedMotion() ?? false; const [values, setValues] = React.useState<SignupValues>({ name: "", email: "", password: "", terms: false }); const [errors, setErrors] = React.useState<Errors>({}); const [attempts, setAttempts] = React.useState(0); const [status, setStatus] = React.useState<"idle" | "submitting" | "done">("idle"); const refs = React.useRef<Partial<Record<FieldName, HTMLElement | null>>>({}); const update = <K extends FieldName>(key: K, value: SignupValues[K]) => { const next = { ...values, [key]: value }; setValues(next); // Re-validate live only after the first submit attempt. if (attempts > 0) setErrors(validateSignup(next)); }; const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); if (status !== "idle") return; const found = validateSignup(values); setErrors(found); setAttempts((n) => n + 1); const first = order.find((key) => found[key]); if (first) { refs.current[first]?.focus(); return; } setStatus("submitting"); try { await onSubmit?.(values); setStatus("done"); } catch { setStatus("idle"); } }; const ids = (key: FieldName) => ({ input: `${id}-${key}`, error: `${id}-${key}-error`, hint: `${id}-${key}-hint` }); const describedBy = (key: FieldName, hint = false) => [hint && ids(key).hint, errors[key] && ids(key).error].filter(Boolean).join(" ") || undefined; const swap = reduceMotion ? { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } } : { initial: { opacity: 0, y: 8 }, animate: { opacity: 1, y: 0 }, exit: { opacity: 0, y: -8 }, }; return ( <div className={cn("grid w-full", className)}> <AnimatePresence initial={false} mode="popLayout"> {status === "done" ? ( <motion.div key="done" {...swap} transition={{ duration: 0.25, ease: "easeOut" }} role="status" className="flex flex-col items-center gap-3 py-10 text-center [grid-area:1/1]" > <motion.span initial={reduceMotion ? false : { scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} transition={{ duration: 0.2, ease: "easeOut", delay: 0.1 }} className="grid size-11 place-items-center rounded-full bg-primary/15 text-primary" > <CheckIcon className="size-5" /> </motion.span> <p className="font-medium">Welcome aboard, {values.name.trim().split(" ")[0]}!</p> <p className="text-sm text-muted-foreground">We sent a confirmation link to {values.email.trim()}.</p> </motion.div> ) : ( <motion.div key="form" {...swap} transition={{ duration: 0.25, ease: "easeOut" }} className="[grid-area:1/1]" > <form noValidate onSubmit={handleSubmit} {...props}> <FieldGroup className="gap-5"> <AnimatedField invalid={!!errors.name} shakeKey={attempts}> <FieldLabel htmlFor={ids("name").input}>Name</FieldLabel> <Input ref={(node) => { refs.current.name = node; }} id={ids("name").input} name="name" autoComplete="name" placeholder="Ada Lovelace" value={values.name} onChange={(e) => update("name", e.target.value)} aria-invalid={!!errors.name || undefined} aria-describedby={describedBy("name")} /> <AnimatedFieldError id={ids("name").error}>{errors.name}</AnimatedFieldError> </AnimatedField> <AnimatedField invalid={!!errors.email} shakeKey={attempts}> <FieldLabel htmlFor={ids("email").input}>Email</FieldLabel> <Input ref={(node) => { refs.current.email = node; }} id={ids("email").input} name="email" type="email" autoComplete="email" placeholder="ada@example.com" value={values.email} onChange={(e) => update("email", e.target.value)} aria-invalid={!!errors.email || undefined} aria-describedby={describedBy("email")} /> <AnimatedFieldError id={ids("email").error}>{errors.email}</AnimatedFieldError> </AnimatedField> <AnimatedField invalid={!!errors.password} shakeKey={attempts}> <FieldLabel htmlFor={ids("password").input}>Password</FieldLabel> <Input ref={(node) => { refs.current.password = node; }} id={ids("password").input} name="password" type="password" autoComplete="new-password" value={values.password} onChange={(e) => update("password", e.target.value)} aria-invalid={!!errors.password || undefined} aria-describedby={describedBy("password", true)} /> <FieldDescription id={ids("password").hint}>At least 8 characters.</FieldDescription> <AnimatedFieldError id={ids("password").error}>{errors.password}</AnimatedFieldError> </AnimatedField> <AnimatedField orientation="horizontal" invalid={!!errors.terms} shakeKey={attempts} className="items-start"> <Checkbox ref={(node) => { refs.current.terms = node; }} id={ids("terms").input} name="terms" checked={values.terms} onCheckedChange={(checked) => update("terms", checked === true)} aria-invalid={!!errors.terms || undefined} aria-describedby={describedBy("terms")} className="mt-0.5" /> <FieldContent> <FieldLabel htmlFor={ids("terms").input} className="font-normal"> I agree to the terms and privacy policy </FieldLabel> <AnimatedFieldError id={ids("terms").error} className="-mt-1.5"> {errors.terms} </AnimatedFieldError> </FieldContent> </AnimatedField> <Button type="submit" loading={status === "submitting"} loadingText="Creating account…" className="w-full"> {submitLabel} </Button> </FieldGroup> </form> </motion.div> )} </AnimatePresence> </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| onSubmit | (values: SignupValues) => void | Promise<void> | — | Called with valid values. A promise keeps the button loading until it settles; a rejection returns to the form. |
| submitLabel | string | "Create account" | Submit button text. |
API Reference
Every part accepts the props of the element it renders. Field renders a div role="group"; FieldLabel is the Radix-powered DuskUI Label.
| Prop | Type | Default | Description |
|---|---|---|---|
| Field orientation | "vertical" | "horizontal" | "responsive" | "vertical" | Stacked, in a row, or a row once the parent FieldGroup is wider than 28rem. |
| Field data-invalid | boolean | — | Tints the label red. Also set aria-invalid on the control. |
| Field data-disabled | boolean | — | Dims the label and description. |
| FieldLegend variant | "legend" | "label" | "legend" | Heading or label-sized legend. |
| FieldError errors | Array<{ message?: string } | undefined> | — | Errors from a validation library. Deduplicated; several render as a list. |
| FieldSeparator children | ReactNode | — | Optional text centered on the line. |
Accessibility
- Link hints and errors to the control with
id+aria-describedby, and setaria-invalidon the control itself — the Field only handles the visuals. FieldErrorandAnimatedFieldErroruserole="alert", so new messages are announced.FieldSet+FieldLegendrender a native fieldset, so screen readers announce the group name before each control.- The Sign-up Form moves focus to the first invalid field on submit and keeps the submit button focusable while loading.
- Shakes and height animations respect prefers-reduced-motion.