# Field

> Label, helper text and error message that wire themselves to the input, textarea or control inside.

Docs: https://plumbago.ochotzas.com/components/field

## Installation

```sh
npx plumbago add field
```

This copies `components/ui/field.tsx` into your project, along with `cn`, and installs `@base-ui/react`.

## Usage

```tsx
import { FieldDescription, FieldLabel, FieldRoot } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

<FieldRoot>
  <FieldLabel>Table name</FieldLabel>
  <Input placeholder="Window 4" />
  <FieldDescription>Guests see this when they scan the QR code.</FieldDescription>
</FieldRoot>
```

## Examples

### Preview

```tsx
import { FieldDescription, FieldLabel, FieldRoot } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

export default function FieldDemo() {
  return (
    <FieldRoot className="max-w-80">
      <FieldLabel>Table name</FieldLabel>
      <Input placeholder="Window 4" />
      <FieldDescription>Guests see this when they scan the QR code.</FieldDescription>
    </FieldRoot>
  )
}
```

### Validation

```tsx
import { FieldError, FieldLabel, FieldRoot } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

export default function FieldValidation() {
  return (
    <FieldRoot className="max-w-80" validationMode="onBlur">
      <FieldLabel>Email for receipts</FieldLabel>
      <Input type="email" required placeholder="name@example.com" />
      <FieldError match="valueMissing">Enter an email address.</FieldError>
      <FieldError match="typeMismatch">That doesn't look like an email address.</FieldError>
    </FieldRoot>
  )
}
```

### Form

```tsx
import { Form } from "@base-ui/react/form"
import { Button } from "@/components/ui/button"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger } from "@/components/ui/select"
import { useState } from "react"

const partySizes = { "2": "2 guests", "3": "3 guests", "4": "4 guests", "5": "5 guests", "6": "6 guests" }

export default function FieldForm() {
  const [attempt, setAttempt] = useState(0)
  const [booked, setBooked] = useState<string | null>(null)

  return (
    <Form
      className="flex w-full max-w-80 flex-col gap-4"
      onSubmit={(event) => {
        event.preventDefault()
        const data = new FormData(event.currentTarget)
        setBooked(`Table for ${data.get("guests")} booked for ${data.get("name")}.`)
      }}
    >
      <FieldRoot name="name" shakeKey={attempt}>
        <FieldLabel>Name</FieldLabel>
        <Input required placeholder="Marta Rossi" autoComplete="name" />
        <FieldError match="valueMissing">Enter the name for the booking.</FieldError>
      </FieldRoot>
      <FieldRoot name="phone" shakeKey={attempt}>
        <FieldLabel>Phone</FieldLabel>
        <Input required type="tel" pattern="[+0-9 ]{7,}" placeholder="+39 333 123 4567" autoComplete="tel" />
        <FieldDescription>We text if the table is ready early.</FieldDescription>
        <FieldError match="valueMissing">Enter a phone number.</FieldError>
        <FieldError match="patternMismatch">Use digits, spaces and an optional +.</FieldError>
      </FieldRoot>
      <FieldRoot name="guests">
        <FieldLabel>Party size</FieldLabel>
        <Select items={partySizes} defaultValue="2" name="guests">
          <SelectTrigger />
          <SelectContent>
            {Object.entries(partySizes).map(([value, label]) => (
              <SelectItem key={value} value={value}>
                {label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </FieldRoot>
      <Button type="submit" size="lg" className="mt-2 w-full" onClick={() => setAttempt((count) => count + 1)}>
        Book table
      </Button>
      {booked && (
        <p
          key={booked}
          className="text-center text-footnote text-ink-2 transition-[opacity,filter] duration-spring ease-spring starting:opacity-0 motion-safe:starting:blur-[4px]"
        >
          {booked}
        </p>
      )}
    </Form>
  )
}
```

### With a textarea

```tsx
import { FieldDescription, FieldLabel, FieldRoot } from "@/components/ui/field"
import { Textarea } from "@/components/ui/textarea"

export default function FieldWithATextarea() {
  return (
    <FieldRoot className="max-w-80">
      <FieldLabel>Note for the kitchen</FieldLabel>
      <Textarea placeholder="No onions on table 4's mains" />
      <FieldDescription>Printed on the ticket.</FieldDescription>
    </FieldRoot>
  )
}
```

## Built on Base UI

Field wraps these Base UI parts and keeps their props:

- [Field](https://base-ui.com/react/components/field)

## Source

```tsx
import { Field } from "@base-ui/react/field"
import { cn } from "@/lib/cn"
import { type ComponentProps, useEffect, useRef } from "react"

type WithClassName<T> = Omit<T, "className"> & { className?: string }

export type FieldRootProps = WithClassName<ComponentProps<typeof Field.Root>> & {
  shakeKey?: number
}

function replayShake(element: HTMLElement) {
  for (const control of element.querySelectorAll<HTMLElement>("[data-invalid], [data-slot=input-group]:has([data-invalid])")) {
    control.style.animation = "none"
    void control.offsetWidth
    control.style.removeProperty("animation")
  }
}

export function FieldRoot({ className, shakeKey, ref, ...props }: FieldRootProps) {
  const elementRef = useRef<HTMLDivElement | null>(null)
  const previousKey = useRef(shakeKey)

  useEffect(() => {
    if (shakeKey === previousKey.current) return
    previousKey.current = shakeKey
    if (elementRef.current) replayShake(elementRef.current)
  }, [shakeKey])

  return (
    <Field.Root
      data-slot="field"
      ref={(node) => {
        elementRef.current = node
        if (typeof ref === "function") ref(node)
        else if (ref) ref.current = node
      }}
      className={cn("group/field flex w-full flex-col items-stretch gap-2", className)}
      {...props}
    />
  )
}

export type FieldLabelProps = WithClassName<ComponentProps<typeof Field.Label>>

export function FieldLabel({ className, ...props }: FieldLabelProps) {
  return <Field.Label data-slot="field-label" className={cn("ml-1 text-footnote font-medium text-ink-2", className)} {...props} />
}

export type FieldDescriptionProps = WithClassName<ComponentProps<typeof Field.Description>>

export function FieldDescription({ className, ...props }: FieldDescriptionProps) {
  return (
    <Field.Description data-slot="field-description" className={cn("ml-1 text-footnote text-ink-2 group-data-invalid/field:hidden", className)} {...props} />
  )
}

export type FieldErrorProps = WithClassName<ComponentProps<typeof Field.Error>>

export function FieldError({ className, ...props }: FieldErrorProps) {
  return (
    <Field.Error
      data-slot="field-error"
      className={cn(
        "ml-1 text-footnote text-danger transition-[opacity,translate,filter] duration-spring ease-spring starting:-translate-y-1 starting:opacity-0 motion-safe:starting:blur-[4px] motion-reduce:starting:translate-y-0",
        className,
      )}
      {...props}
    />
  )
}

export const fieldControlStyle = [
  "w-full rounded-md border-0 bg-fill-field text-body text-ink outline-none placeholder:text-ink-3",
  "transition-shadow duration-fast ease-out focus:ring-2 focus:ring-accent",
  "data-invalid:animate-shake motion-reduce:data-invalid:animate-none data-invalid:ring-2 data-invalid:ring-danger data-invalid:focus:ring-danger",
  "disabled:cursor-default disabled:opacity-40",
]
```
