Field

Wires a label, a description and validation errors to a form control.

FieldError shows the control’s native validation message once the field is invalid, after the first submit or once the person leaves the field. Submit the form empty to see it.

Preview
validation.tsx
import { Button } from "~/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "~/components/ui/field"
import { Input } from "~/components/ui/input"

export default function Example() {
  return (
    <form
      className="grid w-full max-w-sm gap-lg"
      onSubmit={(event) => {
        event.preventDefault()
      }}
    >
      <Field name="username">
        <FieldLabel>Username</FieldLabel>
        <Input required minLength={3} autoComplete="username" />
        <FieldDescription>At least three characters.</FieldDescription>
        <FieldError />
      </Field>
      <Button type="submit" className="justify-self-start">
        Create account
      </Button>
    </form>
  )
}

Field sets and horizontal fields

Group related fields in a FieldSet with a FieldLegend, and stack them in a FieldGroup. orientation="horizontal" puts a checkbox or switch beside its label; wrap the label and a description in FieldContent to keep them together.

Preview
fieldset.tsx
import { Checkbox } from "~/components/ui/checkbox"
import {
  Field,
  FieldContent,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "~/components/ui/field"
import { Input } from "~/components/ui/input"
import { Switch } from "~/components/ui/switch"

export default function Example() {
  return (
    <FieldSet className="w-full max-w-sm">
      <FieldLegend>Edition defaults</FieldLegend>
      <FieldGroup>
        <Field>
          <FieldLabel>Page count</FieldLabel>
          <Input type="number" defaultValue="24" />
        </Field>
        <Field orientation="horizontal">
          <Checkbox defaultChecked />
          <FieldLabel>Run layout checks on save</FieldLabel>
        </Field>
        <Field orientation="horizontal">
          <FieldContent>
            <FieldLabel>Show baselines</FieldLabel>
            <FieldDescription>Draw the baseline grid over every page.</FieldDescription>
          </FieldContent>
          <Switch />
        </Field>
      </FieldGroup>
    </FieldSet>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesLabelform itemTextprimitive
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/field.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/field.tsx
import {
  Field as FieldPrimitive,
  FieldDescription as FieldDescriptionPrimitive,
  FieldError as FieldErrorPrimitive,
  FieldGroup as FieldGroupPrimitive,
  FieldLabel as FieldLabelPrimitive,
  FieldLegend as FieldLegendPrimitive,
  FieldSet as FieldSetPrimitive,
} from "@ui-sdk/react/field"
import type * as React from "react"

import { labelVariants } from "~/components/ui/label"
import { textVariants } from "~/components/ui/text"
import { cn, cnState } from "~/lib/utils"

type FieldProps = React.ComponentProps<typeof FieldPrimitive> & {
  /** `horizontal` puts the control beside its label, for a checkbox or a switch. */
  orientation?: "vertical" | "horizontal"
}

/** Wires a label, a description and errors to the control inside it. */
function Field({ orientation = "vertical", className, ...props }: FieldProps) {
  return (
    <FieldPrimitive
      data-orientation={orientation}
      className={cnState(
        [
          "group/field flex w-full gap-md data-invalid:text-destructive",
          "data-[orientation=vertical]:flex-col",
          "data-[orientation=horizontal]:flex-row data-[orientation=horizontal]:items-center data-[orientation=horizontal]:has-[>[data-slot=field-content]]:items-start",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

/** The label and description beside a horizontal field's control. */
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="field-content"
      className={cn(
        textVariants({ leading: "snug" }),
        "flex flex-1 flex-col gap-xs *:data-[slot=field-description]:mt-0",
        className,
      )}
      {...props}
    />
  )
}

/** Related fields under one legend, like an address. */
function FieldSet({ className, ...props }: React.ComponentProps<typeof FieldSetPrimitive>) {
  return (
    <FieldSetPrimitive
      className={cnState("flex min-w-0 flex-col gap-xl border-0 p-0", className)}
      {...props}
    />
  )
}

/** Names a field set. */
function FieldLegend({ className, ...props }: React.ComponentProps<typeof FieldLegendPrimitive>) {
  return (
    <FieldLegendPrimitive
      className={cnState(
        [textVariants({ size: "md", weight: "medium", family: "heading" }), "mb-md"],
        className,
      )}
      {...props}
    />
  )
}

/** Stacks fields, or a group of checkboxes or switches sharing one label. */
function FieldGroup({ className, ...props }: React.ComponentProps<typeof FieldGroupPrimitive>) {
  return (
    <FieldGroupPrimitive className={cnState("flex w-full flex-col gap-xl", className)} {...props} />
  )
}

/** Names the field's control. */
function FieldLabel({ className, ...props }: React.ComponentProps<typeof FieldLabelPrimitive>) {
  return (
    <FieldLabelPrimitive
      className={cnState(
        [labelVariants(), textVariants({ leading: "snug" }), "flex w-fit"],
        className,
      )}
      {...props}
    />
  )
}

/** Extra help for the field, read out with its control. */
function FieldDescription({
  className,
  ...props
}: React.ComponentProps<typeof FieldDescriptionPrimitive>) {
  return (
    <FieldDescriptionPrimitive
      className={cnState(
        [
          textVariants({ size: "sm", weight: "normal", tone: "muted" }),
          "-mt-2xs text-left [&>a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-foreground",
        ],
        className,
      )}
      {...props}
    />
  )
}

/** Shows the control's validation error once it's invalid. */
function FieldError({ className, ...props }: React.ComponentProps<typeof FieldErrorPrimitive>) {
  return (
    <FieldErrorPrimitive
      className={cnState(
        [textVariants({ size: "sm", weight: "normal" }), "-mt-2xs text-destructive"],
        className,
      )}
      {...props}
    />
  )
}

export {
  Field,
  FieldContent,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSet,
}
export type { FieldProps }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Field

Wires a label, a description and errors to the control inside it.

orientationours

horizontal puts the control beside its label, for a checkbox or a switch.

Type "horizontal" | "vertical" · Default vertical

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldState) => string)

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

disabled

Disables the control, and marks every part.

Type boolean

invalid

Whether the field shows as invalid, when your code decides, like a form library or an error from the server. true shows its errors now, false shows none whatever the browser thinks. Leave it out to show the browser's own validation once a submit finds the field invalid.

Type boolean

name

The name the control submits under, when the control doesn't set its own.

Type string

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldState) => CSSProperties)

FieldContent

The label and description beside a horizontal field's control.

Takes the props of a native div.

FieldDescription

Extra help for the field, read out with its control.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldDescriptionState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldDescriptionState) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldDescriptionState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldDescriptionState) => CSSProperties)

FieldError

Shows the control's validation error once it's invalid.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldErrorState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldErrorState) => string)

match

When this error shows. true shows it always and false never. A validity flag, like "valueMissing", shows it only for that problem of the browser's own validation. Without it, any problem shows it.

Type boolean | ValidityKey

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldErrorState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldErrorState) => CSSProperties)

FieldGroup

Stacks fields, or a group of checkboxes or switches sharing one label.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: {}) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: {}) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<{}>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: {}) => CSSProperties)

FieldLabel

Names the field's control.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldState) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldState) => CSSProperties)

FieldLegend

Names a field set.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldSetState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldSetState) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldSetState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldSetState) => CSSProperties)

FieldSet

Related fields under one legend, like an address.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: FieldSetState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: FieldSetState) => string)

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

disabled

Disables every control inside it, except those in its legend, and leaves them out of the form.

Type boolean

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<FieldSetState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: FieldSetState) => CSSProperties)