Skip to content

Field

Combines a label, a control, a description and an error into one form field, and groups fields into forms.

New supplier

Purchasing reviews every new supplier before the first order.

The site that receives most of the orders.

Installation

pnpm dlx shadcn@latest add @silkware/field

To copy the component by hand, install its dependencies:

pnpm add class-variance-authority cn

Field also uses Label and Separator. Add them if you copy the files by hand:

pnpm dlx shadcn@latest add @silkware/label @silkware/separator

Then copy the source into components/ui/field.tsx:

components/ui/field.tsx
"use client"
import { useMemo } from "react"import { cva, type VariantProps } from "class-variance-authority"import { cn } from "cn"
import { Label } from "@/components/ui/label"import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {  return (    <fieldset      data-slot="field-set"      className={cn(        "flex flex-col gap-6 has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",        className      )}      {...props}    />  )}
function FieldLegend({  className,  variant = "legend",  ...props}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {  return (    <legend      data-slot="field-legend"      data-variant={variant}      className={cn(        "mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base",        className      )}      {...props}    />  )}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="field-group"      className={cn(        "group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 *:data-[slot=field-group]:gap-4",        className      )}      {...props}    />  )}
const fieldVariants = cva(  "group/field flex w-full gap-3 data-[invalid=true]:text-destructive",  {    variants: {      orientation: {        vertical: "flex-col *:w-full [&>.sr-only]:w-auto",        horizontal:          "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",        responsive:          "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",      },    },    defaultVariants: {      orientation: "vertical",    },  })
function Field({  className,  orientation = "vertical",  ...props}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {  return (    <div      role="group"      data-slot="field"      data-orientation={orientation}      className={cn(fieldVariants({ orientation }), className)}      {...props}    />  )}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="field-content"      className={cn(        "group/field-content flex flex-1 flex-col gap-1 leading-snug",        className      )}      {...props}    />  )}
function FieldLabel({  className,  ...props}: React.ComponentProps<typeof Label>) {  return (    <Label      data-slot="field-label"      className={cn(        "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-data-selected:border-primary/30 has-data-selected:bg-primary/5 has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-3 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10 dark:has-data-selected:border-primary/20 dark:has-data-selected:bg-primary/10",        "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",        className      )}      {...props}    />  )}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="field-label"      className={cn(        "flex w-fit items-center gap-2 text-sm font-medium group-data-[disabled=true]/field:opacity-50",        className      )}      {...props}    />  )}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {  return (    <p      data-slot="field-description"      className={cn(        "text-left text-sm leading-normal font-normal text-muted-foreground group-has-data-horizontal/field:text-balance [[data-variant=legend]+&]:-mt-1.5",        "last:mt-0 nth-last-2:-mt-1",        "[&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",        className      )}      {...props}    />  )}
function FieldSeparator({  children,  className,  ...props}: React.ComponentProps<"div"> & {  children?: React.ReactNode}) {  return (    <div      data-slot="field-separator"      data-content={!!children}      className={cn(        "relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",        className      )}      {...props}    >      <Separator className="absolute inset-0 top-1/2" />      {children && (        <span          className="relative mx-auto block w-fit bg-background px-2 text-muted-foreground"          data-slot="field-separator-content"        >          {children}        </span>      )}    </div>  )}
function FieldError({  className,  children,  errors,  ...props}: React.ComponentProps<"div"> & {  errors?: Array<{ message?: string } | undefined>}) {  const content = useMemo(() => {    if (children) {      return children    }
    if (!errors?.length) {      return null    }
    const uniqueErrors = [      ...new Map(errors.map((error) => [error?.message, error])).values(),    ]
    if (uniqueErrors?.length == 1) {      return uniqueErrors[0]?.message    }
    return (      <ul className="ml-4 flex list-disc flex-col gap-1">        {uniqueErrors.map(          (error, index) =>            error?.message && <li key={index}>{error.message}</li>        )}      </ul>    )  }, [children, errors])
  if (!content) {    return null  }
  return (    <div      role="alert"      data-slot="field-error"      className={cn("text-sm font-normal text-destructive", className)}      {...props}    >      {content}    </div>  )}
export {  Field,  FieldLabel,  FieldDescription,  FieldError,  FieldGroup,  FieldLegend,  FieldSeparator,  FieldSet,  FieldContent,  FieldTitle,}

Usage

import {  Field,  FieldContent,  FieldDescription,  FieldError,  FieldGroup,  FieldLabel,  FieldLegend,  FieldSeparator,  FieldSet,  FieldTitle,} from "@/components/ui/field"
<FieldSet>  <FieldLegend>New supplier</FieldLegend>  <FieldGroup>    <Field>      <FieldLabel htmlFor="name">Supplier name</FieldLabel>      <Input id="name" aria-describedby="name-hint" />      <FieldDescription id="name-hint">The legal name.</FieldDescription>    </Field>  </FieldGroup></FieldSet>

The parts are plain elements. Field is a div with role="group", and FieldDescription and FieldError are not connected to the control for you. Give the control an id that matches the htmlFor of the label, and list the ids of the description and the error in its aria-describedby. Without that link, a screen reader announces the label and not the help text.

The same rule holds for every control in the system, with one difference in where the label goes:

ControlLabelDescription and error
Input, Textarea, InputGroup, InputOTP, NativeSelect, Checkbox, SwitchFieldLabel htmlFor and the same id on the controlTheir ids in aria-describedby on the control, and aria-invalid on it when the value is wrong
Select, Combobox, RadioGroup, CheckboxGroup, SliderFieldLabel or Label inside the component, without htmlFor. React Aria names the trigger, input or group from itTheir ids in aria-describedby on the component, which passes them to the trigger, input or group, and isInvalid on it

Never point htmlFor at a SelectTrigger: React Aria names the trigger from its own label and the selected value, so the trigger is announced by its placeholder only.

When React Aria validates the value for you (isRequired or validate on a TextField, Select or RadioGroup inside a React Aria Form), put React Aria's FieldError and Text slot="description" inside the component instead. They take their ids from the component, and FieldError shows the validation message by itself. The forms-01 block is built that way.

The structure of a form:

FieldSet├── FieldLegend├── FieldDescription└── FieldGroup    ├── Field    │   ├── FieldLabel    │   ├── Input, Textarea, Switch, NativeSelect    │   ├── FieldDescription    │   └── FieldError    ├── FieldSeparator    └── Field

Examples

Vertical

The default. The label sits above the control, with the description and error below. Use it for text inputs, selects and textareas.

Three letters and four digits.

Horizontal

The control sits beside its label. Wrap the label and the description in FieldContent so they stack together. Use it for switches, checkboxes and radios.

Email the buyer when the supplier ships an order.

Responsive

The field is vertical in a narrow container and horizontal in a wide one. The switch happens at the width of the FieldGroup that holds it, through a container query, not at the width of the screen.

Shown to every buyer who orders for this site.

Description

FieldDescription carries help that people need before they type: the format, the limit, who sees the value. Link it to the control with aria-describedby.

Counted from the day the supplier confirms the order.

Error

Set data-invalid on the Field and aria-invalid on the control, then show the message in FieldError. It renders with role="alert", so screen readers announce it when it appears, and it renders nothing when it has no content.

Several errors

Pass an errors array instead of children. FieldError removes duplicates, shows one message as text and several as a list.

Disabled

Set data-disabled on the Field and the disabled attribute on the control so the label and the description dim with it.

Only an administrator can move an order to another site.

Field set

FieldSet renders a <fieldset> and FieldLegend its <legend>. Use them to name a group of related fields, such as an address, and for groups of checkboxes or radios.

Delivery address

Where the supplier sends the goods.

Separator

FieldSeparator draws a rule between sections. Pass text, such as "or", to centre it on the rule.

or

Choice card

Wrap a Field in a FieldLabel to make the whole card the click target. The card takes a tint when its radio, checkbox or switch is selected, and a ring when it has focus. Use FieldTitle for the title, because the label is already the card.

Accessibility

KeyAction
TabMoves focus to the next control. Labels, descriptions and legends are not focusable.
ShiftTabMoves focus to the previous control.

The platform provides:

  • The label link through for and id, and the group name from a <fieldset> and its <legend>.
  • The description and error link through aria-describedby, once you write it.
  • Announcement of FieldError as it appears, through role="alert".

You provide:

  • A label for every control, with matching htmlFor and id.
  • aria-describedby on the control that lists the description and error ids.
  • aria-invalid on the control and data-invalid on the field when the value is wrong. The field does not read the validity of the control for you.
  • A FieldSet and FieldLegend for radios and for groups of checkboxes, so the group has a name.

Guidelines

When to use

  • For every control in a form: it gives the label, the help and the error a consistent place.
  • To group fields into sections with a legend.

When not to use

  • For a control outside a form, such as a search box in a toolbar. Use the control with an aria-label, or an Input Group.
  • To title a page section. Use a heading.
  • For a long form that needs steps or progress. Build it from several FieldSet blocks and see Forms.

Content

  • One idea per label, in sentence case, with no colon.
  • Descriptions say what to enter or why it is asked, in one sentence with a full stop.
  • Errors say what is wrong and how to fix it.
  • Put the description above the control for a password rule or a format, where people read it before they type, and below it for everything else.

Errors

Do

Say what is wrong and what to enter.

Don’t

Don’t show a message such as "Invalid input" that does not say what to change.

API reference

Field

Renders a div with role="group". It accepts every div prop.

PropTypeDefaultDescription
orientation?"vertical" | "horizontal" | "responsive""vertical"How the label and the control sit together. Responsive switches at the width of the FieldGroup.
data-invalid?booleanNoneTurns the label and the error to the destructive colour.
data-disabled?booleanNoneDims the label and the description.
className?stringNoneClasses merged after the orientation classes.

FieldSet

Renders a <fieldset> with a column layout. It accepts every fieldset prop.

FieldLegend

Renders a <legend>.

PropTypeDefaultDescription
variant?"legend" | "label""legend"legend is base-sized for a section. label is small and matches a field label.

FieldGroup

Renders a div that stacks fields with a gap and acts as the container for responsive fields. It accepts every div prop.

FieldContent

Renders a div that stacks a label and a description next to a horizontal control. It accepts every div prop.

FieldLabel

Renders a Label with the field styles. It accepts every Label prop. Wrapping a Field in it makes a choice card.

FieldTitle

Renders a div styled like a label, for the title inside a choice card or above a control that has its own accessible name, such as a slider. It accepts every div prop.

FieldDescription

Renders a p of muted help text. It accepts every p prop. Links inside it are underlined.

FieldError

Renders a div with role="alert", or nothing when there is no content. It accepts every div prop.

PropTypeDefaultDescription
children?ReactNodeNoneThe message. When set, it wins over errors.
errors?Array<{ message?: string } | undefined>NoneMessages to show. Duplicates are removed. One message is text and several are a list.

FieldSeparator

Renders a rule between fields. It accepts every div prop.

PropTypeDefaultDescription
children?ReactNodeNoneText centred on the rule, such as or.