Form field
Label, hint and error around any input.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/and the colour tokens go into your CSS.$ pnpm dlx asta-ui@latest add fieldOr install the package
Don’t want the file? Import from
asta-ui/fieldand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-uiimport { Field } from "asta-ui/field";Or copy it by hand
Copy this file. Keep the paths, or fix the
@/imports. Then add the tokens fromglobals.css."use client"; import { Children, cloneElement, isValidElement, useEffect, useId, useRef, type ReactElement, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); export interface FieldProps { label: ReactNode; /** Help text under the input. Replaced by the error while there is one. */ hint?: ReactNode; /** An error message. Each time it changes to a new message the field shakes once. */ error?: ReactNode; required?: boolean; /** Shown on the right of the label, e.g. "Optional" or a character count. */ aside?: ReactNode; className?: string; /** Any single input-like element. It receives `id`, `aria-describedby`, `aria-invalid` and `aria-required`. */ children: ReactElement<Record<string, unknown>>; } /** Label, hint and error around any input, wired up for screen readers. */ export function Field({ label, hint, error, required, aside, className, children }: FieldProps) { const id = useId(); const wrap = useRef<HTMLDivElement>(null); const last = useRef<ReactNode>(null); // Shake once per new error message (Web Animations, so the input keeps focus). useEffect(() => { if (error && error !== last.current && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) { wrap.current?.animate( [{ transform: "none" }, { transform: "translateX(-6px)" }, { transform: "translateX(5px)" }, { transform: "translateX(-3px)" }, { transform: "translateX(2px)" }, { transform: "none" }], { duration: 420, easing: "cubic-bezier(.36,.07,.19,.97)" }, ); } last.current = error ?? null; }, [error]); const child = Children.only(children); const msgId = error ? `${id}-error` : hint ? `${id}-hint` : undefined; const input = isValidElement(child) ? cloneElement(child, { id: (child.props.id as string) ?? id, "aria-describedby": msgId, "aria-invalid": error ? true : undefined, "aria-required": required || undefined, }) : child; const inputId = (child.props.id as string) ?? id; return ( <div className={cx("flex flex-col gap-1.5", className)}> <div className="flex items-baseline justify-between gap-3"> <label htmlFor={inputId} className="text-[13px] font-medium tracking-[-0.01em] text-ink"> {label} {required && ( <span aria-hidden className="ml-0.5 text-ink"> * </span> )} </label> {aside && <span className="text-[12px] tabular-nums text-mute">{aside}</span>} </div> <div ref={wrap}>{input}</div> <div className="grid text-[12.5px] leading-snug"> {error ? ( <p id={`${id}-error`} role="alert" className="flex items-start gap-1.5 text-ink animate-[kit-field-in_.3s_cubic-bezier(.16,1,.3,1)_both]"> <svg viewBox="0 0 24 24" className="mt-px h-3.5 w-3.5 shrink-0" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="12" cy="12" r="8.5" /> <path d="M12 7.5v5" /> <path d="M12 16h.01" /> </svg> {error} </p> ) : hint ? ( <p id={`${id}-hint`} className="text-mute"> {hint} </p> ) : null} </div> <style href="asta-field" precedence="asta">{`@keyframes kit-field-in { from { opacity: 0; transform: translateY(-3px) } to { opacity: 1; transform: none } }`}</style> </div> ); } /** A plain text input styled to match the kit, with error styling driven by `aria-invalid`. */ export const fieldInputClass = "h-10 w-full rounded-lg bg-paper px-3 text-[16px] sm:text-[14px] text-ink outline-none placeholder:text-mute " + "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)] transition-shadow duration-200 " + "hover:shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_24%,transparent)] " + "focus:shadow-[inset_0_0_0_1px_var(--color-brand),0_0_0_3px_color-mix(in_srgb,var(--color-brand)_18%,transparent)] " + "aria-[invalid=true]:shadow-[inset_0_0_0_1.5px_var(--color-ink),0_0_0_3px_color-mix(in_srgb,var(--color-ink)_12%,transparent)]"; export default Field;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Form field component to my project. Label, hint and error around any input. It includes: label, hint, error, required, validation. Install it: ```sh pnpm dlx asta-ui@latest add field --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/field.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { Field, fieldInputClass } from "@/components/astabyte/field"; ``` Usage example and props: https://ui.astabyte.com/field Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<div style="display:grid;gap:20px;max-width:360px"> <div class="asta-field"> <div class="asta-field-head"> <label class="asta-label" for="ex-email">Email<span class="asta-label-required" aria-hidden="true">*</span></label> </div> <label class="asta-input"><input class="asta-input-control" id="ex-email" name="email" type="email" placeholder="[email protected]" autocomplete="email" inputmode="email" autocapitalize="none" spellcheck="false" aria-describedby="ex-email-hint" required></label> <p class="asta-hint" id="ex-email-hint">We never share it.</p> </div> <div class="asta-field"> <div class="asta-field-head"> <label class="asta-label" for="ex-handle">Handle</label> <span class="asta-counter">8/20</span> </div> <label class="asta-input"> <input class="asta-input-control" id="ex-handle" name="handle" value="astabyte" autocomplete="username" autocapitalize="none" spellcheck="false" aria-invalid="true" aria-describedby="ex-handle-error"> <svg class="asta-input-status" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="8" cy="8" r="6.25"/><path d="M8 5v3.5M8 11h.01"/></svg> </label> <p class="asta-error" id="ex-handle-error" role="alert"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="8" cy="8" r="6.25"/><path d="M8 5v3.5M8 11h.01"/></svg>That handle is taken. Try another, like astabyte-studio.</p> </div> </div>
Usage
The demo above, as code.
"use client";
import { useState } from "react";
import { Button } from "@/components/astabyte/button";
import { Field, fieldInputClass } from "@/components/astabyte/field";
type Errors = { email?: string; username?: string };
const check = {
email: (v: string) => (!v.trim() ? "Enter your email." : !/^\S+@\S+\.\S+$/.test(v.trim()) ? "Enter an email like [email protected]." : undefined),
username: (v: string) => (v.length < 3 ? "Use at least 3 characters, like ada-lovelace." : undefined),
};
export default function FieldDemo() {
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [errors, setErrors] = useState<Errors>({});
const [done, setDone] = useState(false);
// Errors show on blur or submit. Typing only clears them, once the value is fixed.
const blur = (k: keyof Errors, v: string) => v && setErrors((x) => ({ ...x, [k]: check[k](v) }));
const edit = (k: keyof Errors, v: string) => {
setDone(false);
if (errors[k] && !check[k](v)) setErrors((x) => ({ ...x, [k]: undefined }));
};
const submit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const next = { email: check.email(email), username: check.username(username) };
setErrors(next);
setDone(!next.email && !next.username);
// Send focus to the first field that needs fixing.
const first = next.email ? "email" : next.username ? "username" : null;
if (first) (e.currentTarget.elements.namedItem(first) as HTMLInputElement | null)?.focus();
};
return (
<div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
<form onSubmit={submit} noValidate className="flex w-full max-w-sm flex-col gap-5">
<Field label="Email" required hint="We'll send a sign-in link here." error={errors.email}>
<input
name="email"
type="email"
autoComplete="email"
inputMode="email"
autoCapitalize="none"
spellCheck={false}
value={email}
onChange={(e) => {
setEmail(e.target.value);
edit("email", e.target.value);
}}
onBlur={() => blur("email", email)}
placeholder="[email protected]"
className={fieldInputClass}
/>
</Field>
<Field label="Username" aside={`${username.length}/20`} hint="Letters, numbers and dashes." error={errors.username}>
<input
name="username"
autoComplete="username"
autoCapitalize="none"
spellCheck={false}
value={username}
maxLength={20}
onChange={(e) => {
const v = e.target.value.replace(/[^a-z0-9-]/gi, "").toLowerCase();
setUsername(v);
edit("username", v);
}}
onBlur={() => blur("username", username)}
placeholder="ada-lovelace"
className={fieldInputClass}
/>
</Field>
<Field label="Company" aside="Optional">
<input name="company" autoComplete="organization" placeholder="Astabyte" className={fieldInputClass} />
</Field>
<Button type="submit" variant={done ? "outline" : "solid"} className="mt-1 w-full">
{done ? "✓ Looks good" : "Create account"}
</Button>
</form>
</div>
);
}