Field
FreeNewWires a label, a hint and an error message to any control. The error takes the hint's place, so the form never jumps.
Installation
First time? Add the @viewport registry to components.json. Setup takes one minute.
Usage
The code behind the preview above.
"use client";
import { useState } from "react";
import { Button } from "@/components/viewport/button";
import { Field } from "@/components/viewport/field";
import { Input } from "@/components/viewport/input";
import { Textarea } from "@/components/viewport/textarea";
export default function FieldDemo() {
const [email, setEmail] = useState("");
const [tried, setTried] = useState(false);
const [sent, setSent] = useState(false);
const problem = !email ? "Enter an email address." : !/^\S+@\S+\.\S+$/.test(email) ? "That does not look like an email address." : undefined;
return (
<form
noValidate
className="flex w-full max-w-sm flex-col gap-4 rounded-2xl border border-border bg-card p-5"
onSubmit={(event) => {
event.preventDefault();
setTried(true);
setSent(!problem);
}}
>
<Field label="Work email" required description="We send the invite here." error={tried ? problem : undefined}>
<Input
type="email"
autoComplete="email"
value={email}
onChange={(event) => {
setEmail(event.target.value);
setSent(false);
}}
/>
</Field>
<Field label="Message" optional description="Shown at the top of the invite email.">
<Textarea autosize rows={2} />
</Field>
<div className="flex items-center justify-between gap-3">
<p role="status" className="text-sm text-muted-foreground">
{sent ? `Invite sent to ${email}.` : ""}
</p>
<Button type="submit">Send invite</Button>
</div>
</form>
);
}Props
| Prop | Type | Default |
|---|---|---|
| label* | stringThe visible label. It is tied to the control inside. | — |
| description | stringA hint shown under the control. | — |
| error | stringAn error message. It replaces the hint, marks the control invalid and is announced. | — |
| required | booleanMarks the label with an asterisk and the control as required for assistive technology. | — |
| optional | booleanAdds "(optional)" after the label. Prefer this when most fields in a form are required. | — |
| hideLabel | booleanKeep the label for screen readers but hide it visually, e.g. for a lone search field. | — |
| children* | React.ReactElementThe control: an Input, Textarea, Select trigger or any element that accepts `id` and ARIA attributes. | — |
| className | string | — |
Accessibility
- Sets id, aria-describedby, aria-invalid and aria-required on the control for you.
- Errors are announced with role=alert, once per new message.
- The required asterisk is hidden from screen readers; aria-required carries it.
- Respects prefers-reduced-motion.