Skip to content
Thrum

Form

A form that validates by field name, renders inline errors beside each field, and focuses a summary listing every issue.

Install

npx shadcn@latest add https://thrumui.dev/r/form.json

Adds components/ui/form.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.

import { Form } from "@/components/ui/form";

Automatically installs icon circle-alert from the icon set.

Data shape

Type
// Passed to Form as `errors`. Keys are field names; an empty object means the values are fine.
type FormErrors = Record<string, string | string[]>;
Sample
const errors: FormErrors = {
  name: "Enter your name.",
  email: ["Enter an email address.", "Use your work address."],
};

Props

PropTypeDefaultDescription
Form: errorsFormErrors–What is wrong, by field name. Each Field with that name turns invalid and its FieldError shows the message. Keep it in state: a new object counts as a new result and moves the focus.
Form: onFormSubmit(values: Record<string, unknown>) => void–Called on submit with the value of every named field, once the fields' own checks pass. The page does not reload.
Form: onSubmit(event: FormEvent) => void–The native event, for a form that posts to a server or a form action.
Form: validationMode"onSubmit" | "onBlur" | "onChange"Default "onSubmit"When fields with a validate function or native constraints check themselves. A Field can set its own.
Form: actionsRefRefObject<{ validate(name?: string): void }>–Runs the fields' own checks from outside, for all fields or one.
Form: soundbooleanDefault truePlay a soft error tone when a submit returns errors, if the visitor has sound on.
Form: classNamestring–Extra classes for the form, merged last. It is a one-column grid with a 16 pixel gap that fills its container.
Form: ...propsComponentProps<"form">–Every other form attribute: action, method, id, aria-label.
FormSummary: titlestringDefault "There is a problem"The line above the list of messages.
FormSummary: classNamestring–Extra classes for the box, merged last.

Motion and sound

Motion

  • Invalid field borders and the summary frame fade over 150 ms. The summary and messages appear and leave at once.
  • Reduced motion: borders change at once.

Sound

  • A calm falling tone when a submit returns errors.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It is a native form element with the browser's own validation bubbles switched off: every message is in the page, next to its field.
  • After a submit that returns errors, the focus moves to the summary. It has the alert role and is named by its title, so a screen reader reads the title and every message.
  • With no summary in the form, the focus moves to the first invalid control instead.
  • Each entry in the summary is a button that moves the focus to the first control with that field's name.
  • A field's message leaves when its value changes. The summary changes only on a submit: it then drops the entries of fields changed since, and takes the focus again while one is left.
  • A field with a validate function or a native constraint stops the submit itself, takes the focus and shows its message. Such errors are not in the summary: return every message through errors when you use one.
  • The summary's border is the destructive colour and its title carries a warning sign, so the state does not rest on colour.
KeysAction
EnterIn a text field: submit the form.
Tab / Shift TabMove through the fields. After a failed submit the focus is on the summary, and Tab goes to its first entry.
Enter / SpaceOn an entry in the summary: move the focus to that field.

Source

components/ui/form.tsx
"use client";

import { createContext, useContext, useEffect, useId, useRef, useState, type ComponentProps, type RefObject } from "react";
import { Form as FormPrimitive } from "@base-ui/react/form";

import { cn } from "@/lib/utils";
import { CircleAlertIcon } from "@/components/icons/circle-alert";
import { play } from "@/lib/thrum-sound";

/** One message, or several, for each field name that has a problem. An empty object means the values are fine. */
export type FormErrors = Record<string, string | string[]>;

export type FormProps = FormPrimitive.Props & {
  /** Play a soft error tone when a submit returns errors, if the visitor has sound on. */
  sound?: boolean;
};

// What the summary lists, and the element it hands back so the form can move the focus there.
const ErrorsContext = createContext<FormProps["errors"]>(undefined);
const BoxContext = createContext<RefObject<HTMLDivElement | null> | null>(null);

const messages = (errors: FormProps["errors"]) =>
  Object.entries(errors ?? {}).flatMap(([name, value]) => [value].flat().flatMap((message) => (message ? { name, message } : [])));

/**
 * A `<form>` that shows errors by field name. Check the values in `onFormSubmit` (by hand or with a schema library),
 * pass what is wrong as `errors`, and each `Field` with that `name` shows its message. A `FormSummary` lists them all and takes the focus.
 */
export function Form({ errors, sound = true, className, onFocus, onKeyDown, onPointerDown, onSubmitCapture, ...props }: FormProps) {
  const box = useRef<HTMLDivElement>(null);
  const prevErrors = useRef(errors);
  // After a failed submit the base form focuses the first invalid control and then selects its text, which focuses it
  // again, all in one go. With a summary in the form the focus belongs there instead, so the summary takes it back,
  // and lets go once the base form is done or the reader presses a key or a button.
  const holding = useRef(false);
  useEffect(() => {
    if (errors !== prevErrors.current) {
      prevErrors.current = errors;
      if (sound && messages(errors).length > 0) play("error");
    }
    if (!box.current) return;
    holding.current = true;
    box.current.focus();
  }, [errors, sound]);

  // A field drops its message once it is changed, and the base form does not ask for new errors while another field
  // still carries one. So at each submit the summary keeps only the entries whose control is still marked invalid.
  const [kept, setKept] = useState<{ of: FormProps["errors"]; names: string[] }>();
  const listed = errors && kept?.of === errors ? Object.fromEntries(kept.names.map((name) => [name, errors[name]])) : errors;

  return (
    <ErrorsContext value={listed}>
      <BoxContext value={box}>
        <FormPrimitive
          data-slot="form"
          errors={errors}
          className={cn("grid w-full min-w-0 gap-4", className)}
          onFocus={(event) => {
            if (holding.current && box.current && (event.target as Node) !== box.current) {
              box.current.focus();
              queueMicrotask(() => (holding.current = false));
            }
            onFocus?.(event);
          }}
          onKeyDown={(event) => {
            holding.current = false;
            onKeyDown?.(event);
          }}
          onPointerDown={(event) => {
            holding.current = false;
            onPointerDown?.(event);
          }}
          onSubmitCapture={(event) => {
            const controls = event.currentTarget.elements;
            const invalid = (name: string) => {
              const control = controls.namedItem(name);
              // What cannot be checked (a group of radios, a control with no name) stays listed.
              return !(control instanceof Element) || control.getAttribute("aria-invalid") === "true";
            };
            setKept({ of: errors, names: Object.keys(listed ?? {}).filter(invalid) });
            // If the base form refuses the submit it focuses the first invalid control: the summary takes that too.
            holding.current = true;
            onSubmitCapture?.(event);
          }}
          {...props}
        />
      </BoxContext>
    </ErrorsContext>
  );
}

export type FormSummaryProps = Omit<ComponentProps<"div">, "title" | "children"> & {
  /** The line above the list. */
  title?: string;
};

/**
 * The list of everything still wrong after the last submit. It is in the page only while the form has `errors` to list.
 * Each entry is a button that moves the focus to its field.
 */
export function FormSummary({ title = "There is a problem", className, ...props }: FormSummaryProps) {
  const box = useContext(BoxContext);
  const titleId = useId();
  // Outside a form there are no errors, so there is nothing to show.
  const list = messages(useContext(ErrorsContext));
  if (list.length === 0) return null;
  return (
    <div
      ref={box}
      data-slot="form-summary"
      role="alert"
      aria-labelledby={titleId}
      tabIndex={-1}
      className={cn(
        "grid gap-1.5 rounded-md border border-destructive p-2.5 text-sm transition-[border-color] duration-150 ease-out motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
        className,
      )}
      {...props}
    >
      <p id={titleId} className="flex items-start gap-2 font-medium text-foreground">
        <CircleAlertIcon size={16} className="mt-0.5 flex-none text-destructive" />
        {title}
      </p>
      <ul className="grid gap-0.5 ps-5">
        {list.map(({ name, message }) => (
          <li key={`${name}: ${message}`}>
            <button
              type="button"
              className="min-h-6 cursor-pointer rounded-sm text-start text-foreground underline underline-offset-4 [overflow-wrap:anywhere] hover:decoration-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
              onClick={(event) => {
                // The first control in this form that carries the field's name.
                const field = event.currentTarget.form?.elements.namedItem(name);
                const control = field instanceof RadioNodeList ? field[0] : field;
                if (control instanceof HTMLElement) control.focus();
              }}
            >
              {message}
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Files and dependencies

Adds
components/ui/form.tsx
Packages
@base-ui/react@1.9.0
Brings along
Sound engine
Icons
circle-alert

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor