Examples
Label and description
Keep the visible label and supporting instruction in one logical group.
Use the name people see in invitations.
Field with a label and description
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}
Required value
Mark required form semantics on the control while keeping the instruction visible.
Required to create a workspace.
Required Field
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}Validation error
A specific error is connected to the invalid control and announced politely.
Use the name people see in invitations.
Invalid Field with a validation error
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}Input and Switch composition
Field groups different controls without taking ownership of business state.
Receive one summary each Monday.
Field compositions for text and binary controls
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}Long supporting content
Long guidance wraps naturally and remains readable at narrow widths.
Explain the trigger, the people affected, and what someone should check before enabling this automation in a production workspace.
Field with long supporting content
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}The Settings form keeps state in the feature: Field describes each relationship, while the screen owns validation, save/discard, and loading behavior. Its Preview and Code/Copy tabs use the same Settings pattern source.
Settings form
Field connects each setting to its label, help, and error while the feature owns validation and saving.
Settings form with Field, Input, validation, and save recovery
"use client";
import { useEffect, useId, useRef, useState } from "react";
import type { FormEvent } from "react";
import { CheckCircleIcon } from "@phuctech/ui/icons";
import { Button } from "@phuctech/ui/components/button";
import {
Card,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@phuctech/ui/components/card";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@phuctech/ui/components/dialog";
import { Field, FieldDescription, FieldError, FieldLabel } from "@phuctech/ui/components/field";
import { Input } from "@phuctech/ui/components/input";
type SettingsValues = {
workspaceName: string;
replyTo: string;
};
type SettingsField = keyof SettingsValues;
type SettingsErrors = Partial<Record<SettingsField, string>>;
type SaveState = "idle" | "saving" | "saved" | "error";
const initialSettings: SettingsValues = {
workspaceName: "PhucTech",
replyTo: "hello@phuctech.dev",
};
const fields: readonly SettingsField[] = ["workspaceName", "replyTo"];
function validateField(field: SettingsField, value: string) {
if (field === "workspaceName" && value.trim().length < 3) {
return "Use at least three characters for the workspace name.";
}
if (field === "replyTo" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim())) {
return "Enter a valid reply-to email, such as name@example.com.";
}
return undefined;
}
function validate(values: SettingsValues): SettingsErrors {
return Object.fromEntries(
fields.flatMap((field) => {
const error = validateField(field, values[field]);
return error ? [[field, error]] : [];
}),
) as SettingsErrors;
}
function focusElement(target: HTMLElement | null) {
target?.focus({ preventScroll: true });
target?.scrollIntoView?.({ block: "center", inline: "nearest" });
}
export function SettingsPattern() {
const [draft, setDraft] = useState<SettingsValues>(() => ({ ...initialSettings }));
const [saved, setSaved] = useState<SettingsValues>(() => ({ ...initialSettings }));
const [errors, setErrors] = useState<SettingsErrors>({});
const [saveState, setSaveState] = useState<SaveState>("idle");
const [serviceError, setServiceError] = useState("");
const [failNextSave, setFailNextSave] = useState(false);
const [discardOpen, setDiscardOpen] = useState(false);
const [invalidSubmitCount, setInvalidSubmitCount] = useState(0);
const [discardCount, setDiscardCount] = useState(0);
const firstInvalidFieldRef = useRef<SettingsField | null>(null);
const nameInputRef = useRef<HTMLInputElement>(null);
const replyInputRef = useRef<HTMLInputElement>(null);
const statusRef = useRef<HTMLDivElement>(null);
const saveTimerRef = useRef<number | null>(null);
const idPrefix = `workspace-settings-${useId().replace(/:/g, "")}`;
const formTitleId = `${idPrefix}-title`;
const nameId = `${idPrefix}-name`;
const nameHelpId = `${idPrefix}-name-help`;
const nameErrorId = `${idPrefix}-name-error`;
const replyId = `${idPrefix}-reply`;
const replyHelpId = `${idPrefix}-reply-help`;
const replyErrorId = `${idPrefix}-reply-error`;
const identityHeadingId = `${idPrefix}-identity`;
const notificationsHeadingId = `${idPrefix}-notifications`;
const saving = saveState === "saving";
const hasChanges = draft.workspaceName !== saved.workspaceName || draft.replyTo !== saved.replyTo;
useEffect(() => {
if (invalidSubmitCount === 0) return;
const target = firstInvalidFieldRef.current === "workspaceName"
? nameInputRef.current
: replyInputRef.current;
focusElement(target);
}, [invalidSubmitCount]);
useEffect(() => {
if (discardCount > 0) focusElement(nameInputRef.current);
}, [discardCount]);
useEffect(() => {
if (saveState === "saving") focusElement(statusRef.current);
}, [saveState]);
useEffect(() => () => {
if (saveTimerRef.current !== null) window.clearTimeout(saveTimerRef.current);
}, []);
function updateValue(field: SettingsField, value: string) {
if (saving) return;
setDraft((current) => ({ ...current, [field]: value }));
setErrors((current) => {
if (!current[field]) return current;
const next = { ...current };
const error = validateField(field, value);
if (error) next[field] = error;
else delete next[field];
return next;
});
setSaveState("idle");
setServiceError("");
}
function validateOnBlur(field: SettingsField) {
if (saving) return;
const error = validateField(field, draft[field]);
setErrors((current) => {
const next = { ...current };
if (error) next[field] = error;
else delete next[field];
return next;
});
}
function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (saving || !hasChanges) return;
const nextErrors = validate(draft);
setErrors(nextErrors);
setServiceError("");
const firstInvalidField = fields.find((field) => nextErrors[field]);
if (firstInvalidField) {
firstInvalidFieldRef.current = firstInvalidField;
setInvalidSubmitCount((count) => count + 1);
setSaveState("error");
return;
}
const nextValues = {
workspaceName: draft.workspaceName.trim(),
replyTo: draft.replyTo.trim(),
};
const shouldFail = failNextSave;
setFailNextSave(false);
setSaveState("saving");
saveTimerRef.current = window.setTimeout(() => {
saveTimerRef.current = null;
if (shouldFail) {
setServiceError("The simulated save failed. Your changes are still here; try again.");
setSaveState("error");
return;
}
setSaved(nextValues);
setDraft(nextValues);
setSaveState("saved");
}, 450);
}
function handleDiscard() {
if (saving) return;
setDraft({ ...saved });
setErrors({});
setServiceError("");
setFailNextSave(false);
setSaveState("idle");
setDiscardOpen(false);
setDiscardCount((count) => count + 1);
}
return (
<Card className="w-full max-w-2xl min-w-0">
<form onSubmit={handleSubmit} noValidate aria-labelledby={formTitleId}>
<CardHeader>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<CardTitle id={formTitleId}>Workspace settings</CardTitle>
<CardDescription>
Edit this local example. Saving updates its snapshot without making a backend request.
</CardDescription>
</div>
{hasChanges ? (
<span className="rounded-full border border-[color:var(--color-warning-border)] bg-[color:var(--color-warning-bg)] px-2 py-1 text-xs font-medium text-[color:var(--color-warning-text)]">
Unsaved changes
</span>
) : null}
</div>
</CardHeader>
<CardContent className="grid min-w-0 gap-6">
<section className="grid min-w-0 gap-4" aria-labelledby={identityHeadingId}>
<div>
<h4 id={identityHeadingId} className="text-sm font-semibold text-foreground">
Workspace identity
</h4>
<p className="mt-1 text-sm text-muted-foreground">
This name appears in invitations and project headers.
</p>
</div>
<Field invalid={Boolean(errors.workspaceName)}>
<FieldLabel htmlFor={nameId}>Workspace name</FieldLabel>
<Input
ref={nameInputRef}
id={nameId}
name="workspaceName"
value={draft.workspaceName}
onChange={(event) => updateValue("workspaceName", event.target.value)}
onBlur={() => validateOnBlur("workspaceName")}
aria-invalid={Boolean(errors.workspaceName) || undefined}
aria-describedby={errors.workspaceName ? `${nameHelpId} ${nameErrorId}` : nameHelpId}
disabled={saving}
required
/>
<FieldDescription id={nameHelpId}>Use a name your team will recognize.</FieldDescription>
<div className="min-h-10 sm:min-h-5">
<FieldError id={nameErrorId} match={Boolean(errors.workspaceName)}>
{errors.workspaceName}
</FieldError>
</div>
</Field>
</section>
<section
className="grid min-w-0 gap-4 border-t border-border pt-5"
aria-labelledby={notificationsHeadingId}
>
<div>
<h4 id={notificationsHeadingId} className="text-sm font-semibold text-foreground">
Notifications
</h4>
<p className="mt-1 text-sm text-muted-foreground">
Choose where workspace activity replies should go.
</p>
</div>
<Field invalid={Boolean(errors.replyTo)}>
<FieldLabel htmlFor={replyId}>Reply-to email</FieldLabel>
<Input
ref={replyInputRef}
id={replyId}
name="replyTo"
type="email"
value={draft.replyTo}
onChange={(event) => updateValue("replyTo", event.target.value)}
onBlur={() => validateOnBlur("replyTo")}
aria-invalid={Boolean(errors.replyTo) || undefined}
aria-describedby={errors.replyTo ? `${replyHelpId} ${replyErrorId}` : replyHelpId}
disabled={saving}
required
/>
<FieldDescription id={replyHelpId}>
Replies from activity emails use this address.
</FieldDescription>
<div className="min-h-10 sm:min-h-5">
<FieldError id={replyErrorId} match={Boolean(errors.replyTo)}>
{errors.replyTo}
</FieldError>
</div>
</Field>
</section>
<div
ref={statusRef}
role="status"
aria-live="polite"
aria-atomic="true"
tabIndex={-1}
className="min-h-5 min-w-0 break-words text-sm"
>
{saving ? (
<p className="text-muted-foreground">Saving settings in this example.</p>
) : saveState === "saved" ? (
<p className="flex items-center gap-2 text-[color:var(--color-success-text)]">
<CheckCircleIcon aria-hidden="true" className="size-4 shrink-0" />
Saved to this example’s local snapshot. No backend request was made.
</p>
) : serviceError ? (
<p className="text-destructive">{serviceError}</p>
) : failNextSave ? (
<p className="text-muted-foreground">The next save will fail in this example.</p>
) : null}
</div>
</CardContent>
<CardFooter className="flex-wrap">
<Button
type="submit"
loading={saving}
loadingLabel="Saving settings"
disabled={!hasChanges}
>
Save changes
</Button>
<Dialog open={discardOpen} onOpenChange={setDiscardOpen}>
<DialogTrigger
render={
<Button type="button" variant="outline" disabled={!hasChanges || saving}>
Discard changes
</Button>
}
/>
<DialogContent>
<DialogHeader>
<DialogTitle>Discard unsaved changes?</DialogTitle>
<DialogDescription>
Restore the last saved workspace name and reply-to email. Your current draft will be lost.
</DialogDescription>
</DialogHeader>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" autoFocus>Keep editing</Button>} />
<Button type="button" variant="destructive" onClick={handleDiscard}>
Discard changes
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Button
type="button"
variant="ghost"
onClick={() => setFailNextSave(true)}
disabled={!hasChanges || saving || failNextSave}
>
Simulate next save failure
</Button>
</CardFooter>
</form>
</Card>
);
}
When to use
Use Field for one logical input and its guidance. It works with Input and other native or Base UI controls; validation remains the responsibility of the form or feature. For a binary setting, compose Field with Switch so the label and description stay connected while the feature owns the setting state.
Usage
import {
Field,
FieldControl,
FieldDescription,
FieldError,
FieldLabel,
} from "@phuctech/ui/components/field";
export function Example() {
return (
<Field invalid>
<FieldLabel>Workspace name</FieldLabel>
<FieldControl defaultValue="PhucTech" aria-invalid="true" />
<FieldDescription>Use the name people see in invitations.</FieldDescription>
<FieldError match>Choose a name with at least three characters.</FieldError>
</Field>
);
}
Use FieldControl when the Base UI field should own the input relationship. Use Input inside Field when you need the Input API, and connect IDs explicitly when you control the validation message.
API
Tokens
Accessibility
- Keep the visible label, control, and error in one logical group.
- Use
aria-invalidonly when the value is invalid, and connect the explanation witharia-describedby. - Do not announce validation on every keystroke unless the task genuinely benefits from live feedback.
Do and don’t
Let the feature own the rule and loading state; let Field own the accessible grouping.
Put business requests, fetch calls, or form submission logic inside Field.