Menu

Components

Form

Holds fields and sends them together, checking them first and showing what is wrong where it is wrong.

Introduction

A form is what turns a set of fields into one thing that can be sent. It keeps them in even space, checks them before they are sent, shows each error on the field it belongs to, and can show an error of a server the same way. It works with every field of centerUI: Text Field, Select, Checkbox, Radio Group, Date Field, and the others.

  • Fields are checked before the form is sent. The one that is wrong takes the focus, and onSubmit is called only when all are valid.
  • validationErrors puts the errors of a server on the fields with that name, and each goes away when the person changes the field. FormError is for an error of the whole form.
  • Return a promise from onSubmit and FormSubmit shows a loader, and cannot be pressed again, until it is done.
  • Sections with a title, a description and columns, that can be turned off as a whole, and a row for the buttons.
  • Built on react-aria's Form. Fields take their validationBehavior from it: native (the default) shows errors when the form is sent, aria as the person types.

Call event.preventDefault() in onSubmit when you send the data yourself. Without it the browser sends the form to action and loads the page again.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

FormSubmit is a Button, so copy that too. Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/form-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Form. The form stacks its fields with a gap (`spacing`); a section
// is a fieldset with a title and its own grid of fields; the actions are a row
// of buttons.
export const formStyles = tv({
  slots: {
    root: "flex w-full flex-col",
    section: "m-0 flex min-w-0 flex-col gap-4 border-0 p-0 disabled:opacity-60",
    legend: "mb-0 p-0 text-base font-semibold leading-snug",
    sectionDescription: "m-0 -mt-2 text-sm text-muted-fg",
    fields: "grid gap-4",
    actions: "flex flex-wrap items-center gap-3",
    error:
      "flex items-start gap-2 rounded-xl border border-danger/40 bg-danger/8 px-3.5 py-3 text-sm text-danger",
  },
  variants: {
    spacing: {
      sm: { root: "gap-4" },
      md: { root: "gap-6" },
      lg: { root: "gap-8" },
    },
    align: {
      start: { actions: "justify-start" },
      center: { actions: "justify-center" },
      end: { actions: "justify-end" },
      between: { actions: "justify-between" },
    },
  },
  defaultVariants: { spacing: "md", align: "start" },
});

2. Add the Form file

src/components/ui/form/form.tsxShow code
"use client";

import {
  createContext,
  type FormEvent,
  type ReactNode,
  useContext,
  useId,
  useState,
} from "react";
import {
  Form as AriaForm,
  type FormProps as AriaFormProps,
} from "react-aria-components";
import { AlertTriangleIcon } from "@/components/icons";
import { Button, type ButtonProps } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { formStyles } from "@/types/form-styles";

const FormContext = createContext({ isSubmitting: false });

/**
 * Whether the form around it is being sent: `true` from when a submit handler
 * that returns a promise starts until it is done. Use it for something that
 * should wait while the form is sent, other than `FormSubmit`.
 */
export function useFormSubmitting() {
  return useContext(FormContext).isSubmitting;
}

export interface FormProps
  extends Omit<AriaFormProps, "className" | "onSubmit" | "children"> {
  /**
   * Called when the form is submitted, and only when every field is valid: the
   * browser does not submit an invalid one. Call `event.preventDefault()` to send
   * the data yourself. When it returns a promise, the form is being sent until
   * the promise is done, and `FormSubmit` shows a loader.
   */
  // biome-ignore lint/suspicious/noConfusingVoidType: a handler may return nothing, or a promise
  onSubmit?: (event: FormEvent<HTMLFormElement>) => void | Promise<unknown>;
  /** The space between the fields, sections and actions. Defaults to `md`. */
  spacing?: "sm" | "md" | "lg";
  className?: string;
  children: ReactNode;
}

/**
 * A form: the element that holds fields and sends them together. It stacks what
 * is inside with an even space, and adds what the fields need to work as one:
 * validation before submitting (each field shows its own error, and the first
 * one that is wrong takes the focus), errors from a server put on the fields they
 * belong to, and a submit button that shows a loader while the form is sent.
 *
 * Built on react-aria's Form, so the fields (TextField, Select, Checkbox, the
 * date fields...) take their `validationBehavior` from it, and the errors of
 * `validationErrors` are put on the field with that `name` and go away when the
 * person changes it.
 *
 * @example
 * <Form onSubmit={async (event) => { event.preventDefault(); await save(new FormData(event.currentTarget)); }}>
 *   <TextField name="email" label="Email" type="email" isRequired />
 *   <FormActions><FormSubmit>Save</FormSubmit></FormActions>
 * </Form>
 */
export function Form({
  onSubmit,
  spacing,
  className,
  children,
  ...props
}: FormProps) {
  const [isSubmitting, setSubmitting] = useState(false);
  const styles = formStyles({ spacing });

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    const result = onSubmit?.(event);
    if (result && typeof (result as Promise<unknown>).then === "function") {
      setSubmitting(true);
      (result as Promise<unknown>).then(
        () => setSubmitting(false),
        () => setSubmitting(false),
      );
    }
  }

  return (
    <FormContext.Provider value={{ isSubmitting }}>
      <AriaForm
        {...props}
        onSubmit={handleSubmit}
        className={cn(styles.root(), className)}
      >
        {children}
      </AriaForm>
    </FormContext.Provider>
  );
}

export interface FormSectionProps {
  /** The title of the group of fields. It is the legend of the fieldset, so a screen reader says it with each field. */
  title?: ReactNode;
  /** A line under the title that says more. */
  description?: ReactNode;
  /** The number of fields in a row. Defaults to `1`. For a row that changes with the screen, leave it and put grid classes in `fieldsClassName`. */
  columns?: 1 | 2 | 3 | 4;
  /** Turns off every field in it, and dims them. */
  isDisabled?: boolean;
  /** Names the group for a screen reader when it has no `title`. */
  "aria-label"?: string;
  className?: string;
  /** Classes for the grid that holds the fields. */
  fieldsClassName?: string;
  children: ReactNode;
}

/**
 * A group of fields that belong together, such as "Account" or "Shipping
 * address", with a title, a line of description, and if you like more than one
 * field to a row. It is a fieldset, so a screen reader says the title with each
 * field, and `isDisabled` turns them all off at once.
 */
export function FormSection({
  title,
  description,
  columns = 1,
  isDisabled,
  "aria-label": ariaLabel,
  className,
  fieldsClassName,
  children,
}: FormSectionProps) {
  const styles = formStyles();
  const descriptionId = useId();

  return (
    <fieldset
      disabled={isDisabled}
      aria-label={title ? undefined : ariaLabel}
      aria-describedby={description ? descriptionId : undefined}
      className={cn(styles.section(), className)}
    >
      {title ? <legend className={styles.legend()}>{title}</legend> : null}
      {description ? (
        <p id={descriptionId} className={styles.sectionDescription()}>
          {description}
        </p>
      ) : null}
      <div
        className={cn(styles.fields(), fieldsClassName)}
        style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
      >
        {children}
      </div>
    </fieldset>
  );
}

export interface FormActionsProps {
  /** Where the buttons go: at the start, the center or the end, or the first at the start and the rest at the end. Defaults to `start`. */
  align?: "start" | "center" | "end" | "between";
  className?: string;
  children: ReactNode;
}

/** A row for the buttons of the form: send, cancel, reset. */
export function FormActions({ align, className, children }: FormActionsProps) {
  const styles = formStyles({ align });
  return <div className={cn(styles.actions(), className)}>{children}</div>;
}

export interface FormSubmitProps
  extends Omit<ButtonProps, "type" | "children"> {
  /** What it says. Defaults to "Submit". */
  children?: ReactNode;
}

/**
 * The button that sends the form. It shows a loader, and cannot be pressed
 * again, while the `onSubmit` of the form is working (when it returns a
 * promise). It is a `Button`, so it takes its variants and sizes.
 */
export function FormSubmit({ children = "Submit", ...props }: FormSubmitProps) {
  const isSubmitting = useFormSubmitting();
  return (
    <Button {...props} type="submit" isPending={isSubmitting}>
      {children}
    </Button>
  );
}

export interface FormErrorProps {
  /** What went wrong with the form as a whole, such as "The email or the password is wrong". Nothing is shown while it is empty. */
  children?: ReactNode;
  className?: string;
}

/**
 * A message for an error that belongs to the whole form and not to a field: the
 * server said no, or the network is down. It is announced to a screen reader
 * when it shows up.
 */
export function FormError({ children, className }: FormErrorProps) {
  const styles = formStyles();
  if (!children) return null;
  return (
    <div role="alert" className={cn(styles.error(), className)}>
      <AlertTriangleIcon
        aria-hidden="true"
        className="mt-0.5 size-4 shrink-0"
      />
      <div>{children}</div>
    </div>
  );
}

3. Use it

import {
  Form,
  FormActions,
  FormError,
  FormSection,
  FormSubmit,
} from "@/components/ui/form/form";

Anatomy

A form, with the fields in it and a row for the buttons.

<Form onSubmit={save} validationErrors={serverErrors}>
  <FormError>{message}</FormError>
  <FormSection title="Account" description="How you sign in." columns={2}>
    <TextField name="email" label="Email" type="email" isRequired />
  </FormSection>
  <FormActions align="end">
    <Button type="reset" variant="ghost">Reset</Button>
    <FormSubmit>Save</FormSubmit>
  </FormActions>
</Form>
PartRendered asNotes
FormformStacks what is in it, checks every field before it is sent, puts the errors of a server on the fields, and knows when it is being sent.
FormErrordiv, role alertA message for an error of the whole form. It shows nothing while it is empty.
FormSectionfieldsetA titled group of fields, with a grid of columns. It can be turned off as a whole.
FormActionsdivA row for the buttons.
FormSubmitbutton, type submitThe button that sends the form. It shows a loader while the form is sent.

Keyboard

KeyWhat it does
EnterIn a field, sends the form (or, in a text area, adds a line).
TabMoves between the fields, and to the buttons.
Enter or SpaceOn a button, presses it.

Examples

Usage

Send it with a field empty, and the first one that is wrong takes the focus and says why. The data is what the fields have as name and value.

Validation

Fields can be isRequired, have a minLength, a pattern, or a validate function that returns a message. errorMessage can be a function that reads why the field is wrong. Change validationBehavior to see the difference.

At least 3 letters or numbers.

Errors from a server

validationErrors is an object of messages by field name. Each shows on its field and goes away when it is changed. Anything that is not about one field goes in FormError.

Try taken@example.com, down@example.com or another.

While it is sent

An onSubmit that returns a promise, such as an async function, keeps FormSubmit pending until it is done.

Saved 0 times

Sections

A section is a fieldset with a title, a description and columns. isDisabled turns off every field in it.

Account

How you sign in.

Shipping address

Where the order goes.

Country

Actions

Where the buttons go.

Spacing

The space between fields, sections and actions.

Field
Field
Actions
sm
Field
Field
Actions
md
Field
Field
Actions
lg

Component API

Each part takes the props of its table.

Form

PropTypeDefault
onSubmit(event) => void | Promise-
validationBehavior"native" | "aria""native"
validationErrorsRecord<string, string | string[]>-
onReset(event) => void-
onInvalid(event) => void-
actionstring | function-
spacing"sm" | "md" | "lg""md"
aria-labelstring-
classNamestring-

FormSection

PropTypeDefault
titleReactNode-
descriptionReactNode-
columns1 | 2 | 3 | 41
isDisabledbooleanfalse
aria-labelstring-
classNamestring-
fieldsClassNamestring-

FormActions

PropTypeDefault
align"start" | "center" | "end" | "between""start"
classNamestring-

FormSubmit

PropTypeDefault
childrenReactNode"Submit"
…restthe props of Button, except type-

FormError

PropTypeDefault
childrenReactNode-
classNamestring-

useFormSubmitting() gives true while the form around it is being sent, for anything that should wait with the button.