Field
A label, one control and an optional hint or error, wired up for screen readers.
Include https://
That address isn't reachable. Check the URL and try again.
Install
$ npx shadcn@latest add @nudgekit/fieldOr with no config: npx shadcn@latest add https://ui.nudgekit.app/r/field.json
Usage
usage.tsx
import { Field } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
<Field label="Website URL" htmlFor="url" hint="Include https://">
<Input id="url" mono />
</Field>
<Field label="Webhook" htmlFor="hook" error="That address isn't reachable.">
<Input id="hook" />
</Field>Do
- Give every form control a Field.
- Write errors as what happened, then what to do.
Don't
- Start errors with "Error:".
- Show a hint and an error at the same time.
Code
What the CLI writes into your project. It is yours to change.
components/ui/field.tsx
import * as React from "react";
import { cn } from "@/lib/utils";
export interface FieldProps extends React.HTMLAttributes<HTMLDivElement> {
label: string;
/** The id of the control inside, so the label is linked to it. */
htmlFor: string;
hint?: string;
error?: string;
}
/** A label, one control and an optional hint or error. Every form control sits in a Field. */
function Field({ label, htmlFor, hint, error, className, children, ...props }: FieldProps) {
const describedBy = error ? `${htmlFor}-error` : hint ? `${htmlFor}-hint` : undefined;
return (
<div data-slot="field" className={cn("flex flex-col gap-1.5", className)} {...props}>
<label htmlFor={htmlFor} className="text-sm font-medium text-foreground">
{label}
</label>
{React.isValidElement<{ "aria-describedby"?: string; "aria-invalid"?: boolean }>(children)
? React.cloneElement(children, {
"aria-describedby": describedBy,
"aria-invalid": error ? true : undefined,
})
: children}
{error ? (
<p id={`${htmlFor}-error`} className="text-[13px] text-danger">
{error}
</p>
) : hint ? (
<p id={`${htmlFor}-hint`} className="text-[13px] text-muted-foreground">
{hint}
</p>
) : null}
</div>
);
}
export { Field };