Skip to main content
Decoderen
Browse documentation

FormField

Use for a labelled native text input, textarea or select within a form: Material 3's outlined text field with a floating label.

Default

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="default-name" label="Name" />

Input types

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="type-email" label="Email" type="email" autocomplete="email" />
<FormField name="type-tel" label="Telephone" type="tel" autocomplete="tel" />
<FormField name="type-url" label="Website" type="url" autocomplete="url" />

Required

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="required-name" label="Name" required />
<FormField name="optional-name" label="Name" />

Hint and error

Feedback is supplied by the caller; these errors are static examples.

Use your work email.

Enter a valid email address.

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="hint-email" label="Email" type="email" hint="Use your work email." />
<FormField name="error-email" label="Email" type="email" error="Enter a valid email address." />

Select

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="select-option" label="Option" type="select" options={[{ value: "first", label: "First option" }, { value: "second", label: "Second option" }]} />

Textarea rows

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="rows-default" label="Default rows" type="textarea" />
<FormField name="rows-three" label="Three rows" type="textarea" rows={3} />
<FormField name="rows-six" label="Six rows" type="textarea" rows={6} />

Disabled

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="disabled-input" label="Disabled input" disabled />
<FormField name="disabled-select" label="Disabled select" type="select" disabled />
<FormField name="disabled-textarea" label="Disabled textarea" type="textarea" disabled />

Compact

Show code
Example.astroAstro
---
import FormField from '@dhekode/ui/primitives/FormField.tsx';
---

<FormField name="compact-search" label="Search" size="sm" placeholder="Search" defaultValue="Invoices" />
API reference
name

Type: string

Default: required

Creates the submitted name and, unless `id` is set, the field-{name} ID.

id

Type: string

Default: field-{name}

Control ID; set it when two forms on one page share a field name.

label

Type: string

Default: required

Visible accessible label; optional fields receive an (optional) suffix.

type

Type: 'text' | 'email' | 'password' | 'tel' | 'url' | 'date' | 'time' | 'textarea' | 'select'

Default: 'text'

Chooses the native control. Date and time always show their format, so their label stays floated.

required

Type: boolean

Default: false

Adds native required validation.

hint

Type: string

Default: unset

Supporting instructions below the control.

error

Type: string

Default: unset

Nonempty feedback sets aria-invalid. The component does not calculate or clear errors.

autocomplete

Type: string

Default: unset

Native autocomplete hint for inputs and textarea; not forwarded to select.

options

Type: readonly { value: string; label: string }[]

Default: []

Select choices. The component already inserts an empty Select an option entry.

emptyLabel

Type: string | null

Default: 'Select an option'

A select's first, empty choice (No vendor); null leaves it out when a value is always set.

rows

Type: number

Default: 5

Textarea height in rows.

size

Type: 'md' | 'sm'

Default: 'md'

sm is a compact single-line input at chip height with a screen-reader-only label; text-like inputs only.

placeholder

Type: string

Default: unset

Size sm only: the hint shown in the empty field. Size md uses a blank placeholder for its floating label.

defaultValue

Type: string

Default: unset

Initial value of an input, textarea or select; the field stays uncontrolled.

inputMode

Type: 'text' | 'decimal' | 'numeric' | 'email' | 'tel' | 'url'

Default: unset

Virtual keyboard hint for an input.

maxLength

Type: number

Default: unset

Maximum number of characters in an input or textarea.

onInvalid / onBlur / onInput

Type: (event) => void

Default: unset

For a form that words the browser's checks itself: prevent the bubble on invalid, re-check on blur and input, and pass the message as error. Needs a React island.

trailing

Type: ReactNode

Default: unset

An action inside a single-line input's end, such as a password's show button (an IconButton, size sm); the input keeps clear of it.

ref

Type: Ref<HTMLInputElement>

Default: unset

Reaches the input only; needs a React island.

disabled

Type: boolean

Default: false

Native disabled control; excluded from focus and form submission.

className

Type: string | undefined

Default: unset

Adds classes to the React component root, after its own utilities. React components take className, not class.

Slots: None. The component owns its label and feedback structure.

The label rests inside an empty field and floats into the border on focus or once filled, in CSS. The field uses a blank placeholder for this, so only size sm takes a placeholder, and there is no loading or success prop. Validation and submission belong to the feature and server. Do not repeat the empty select option.

Original component source
packages/ui/src/primitives/FormField.tsxAstro
import type { FormEvent, ReactNode, Ref } from 'react';
import Icon from '@dhekode/icons/Icon.tsx';
import { classNames } from '@dhekode/utils/class-names';

type Size = 'md' | 'sm';

type FieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
type FieldHandler = ((event: FormEvent<FieldElement>) => void) | undefined;

interface Option {
  value: string;
  label: string;
}

export interface FormFieldProps {
  name: string;
  /** Control id; defaults to `field-{name}`. Set it when two forms on a page share a name. */
  id?: string | undefined;
  label: string;
  /** Date and time inputs always show their format, so their label stays floated. */
  type?:
    | 'text'
    | 'email'
    | 'password'
    | 'tel'
    | 'url'
    | 'date'
    | 'time'
    | 'textarea'
    | 'select'
    | undefined;
  required?: boolean | undefined;
  hint?: string | undefined;
  error?: string | undefined;
  autocomplete?: string | undefined;
  options?: readonly Option[] | undefined;
  /** A select's first, empty choice ("No vendor"); null leaves it out when a value is always set. */
  emptyLabel?: string | null | undefined;
  rows?: number | undefined;
  disabled?: boolean | undefined;
  /**
   * md is Material 3's outlined field with a floating label. sm is a compact single-line input
   * at the chip height for toolbars: its label stays for assistive technology only, so give it
   * a `placeholder` that shows what to type. Text-like inputs only.
   */
  size?: Size | undefined;
  placeholder?: string | undefined;
  defaultValue?: string | undefined;
  inputMode?: 'text' | 'decimal' | 'numeric' | 'email' | 'tel' | 'url' | undefined;
  maxLength?: number | undefined;
  ref?: Ref<HTMLInputElement> | undefined;
  /**
   * An action inside the field's end, such as a password's show button (an IconButton). The
   * input keeps clear of it. Single-line inputs only.
   */
  trailing?: ReactNode;
  /**
   * Validation hooks for a form that words the browser's checks itself: `onInvalid` (call
   * `preventDefault` to drop the browser's bubble), and `onBlur` and `onInput` to re-check.
   */
  onInvalid?: FieldHandler;
  onBlur?: FieldHandler;
  onInput?: FieldHandler;
  className?: string | undefined;
}

/**
 * Material 3's outlined text field. The control sits on the surface; focus draws a 2px outline
 * (the 1px border plus an inset ring, so nothing shifts) and keeps a transparent outline that
 * forced-colors mode paints. Disabled fields keep the surface fill, as Material 3 does, so the
 * label's notch still matches, and stay fully opaque against WebKit's dimming.
 */
const control =
  'dk-field__control peer col-start-1 row-start-1 w-full min-w-0 border-(length:--dk-border-width-hairline) border-solid border-surface-muted bg-surface-bg px-md leading-snug text-surface-text transition-colors duration-(--dk-motion-duration-quick) ease-out hover:border-surface-text focus:border-surface-focus focus:ring-1 focus:ring-surface-focus focus:outline-hidden focus:ring-inset aria-invalid:border-surface-error aria-invalid:focus:ring-surface-error disabled:cursor-not-allowed disabled:border-disabled-border disabled:text-disabled-text disabled:opacity-100';

/** Component tokens per size: the shape, the type and how the placeholder shows. */
const controlSizes: Record<Size, string> = {
  md: 'rounded-sm py-md text-body placeholder:text-transparent',
  sm: 'h-(--dk-layout-control-height-sm) rounded-full py-0 text-body-sm placeholder:text-surface-muted',
};

/**
 * The label floats on the border, notched by the surface colour, and rests inside the field
 * while an input or textarea is empty and unfocused (its blank placeholder is shown). A select
 * always shows its prompt, so its label stays floated.
 */
const floatingLabel =
  'dk-field__label pointer-events-none col-start-1 row-start-1 ms-sm self-start justify-self-start -translate-y-1/2 bg-surface-bg px-2xs text-label leading-snug font-medium text-surface-muted transition-all duration-(--dk-motion-duration-quick) ease-out peer-placeholder-shown:translate-y-md peer-placeholder-shown:text-body peer-placeholder-shown:font-regular peer-focus:-translate-y-1/2 peer-focus:text-label peer-focus:font-medium peer-focus:text-surface-focus peer-aria-invalid:text-surface-error peer-disabled:text-disabled-text';

/** Accessible form field: visible label, hint and error wired with aria-describedby. */
export default function FormField({
  name,
  id = `field-${name}`,
  label,
  type = 'text',
  required = false,
  hint,
  error,
  autocomplete,
  options = [],
  emptyLabel = 'Select an option',
  rows = 5,
  disabled = false,
  size = 'md',
  placeholder,
  defaultValue,
  inputMode,
  maxLength,
  ref,
  trailing,
  onInvalid,
  onBlur,
  onInput,
  className,
}: FormFieldProps) {
  const compact = size === 'sm' && type !== 'textarea' && type !== 'select';
  const hintId = hint ? `${id}-hint` : undefined;
  const errorId = error ? `${id}-error` : undefined;
  const describedBy = [hintId, errorId].filter(Boolean).join(' ') || undefined;
  const shared = {
    id,
    name,
    required,
    disabled,
    'aria-describedby': describedBy,
    'aria-invalid': error ? true : undefined,
    onInvalid,
    onBlur,
    onInput,
  };

  return (
    <div
      className={classNames('dk-field grid min-w-0 grid-cols-1 content-start gap-xs', className)}
      data-invalid={error ? '' : undefined}
    >
      <div className="dk-field__box grid min-w-0 grid-cols-1">
        {type === 'textarea' ? (
          <textarea
            {...shared}
            className={classNames(control, controlSizes.md, 'resize-y')}
            rows={rows}
            autoComplete={autocomplete}
            placeholder=" "
            defaultValue={defaultValue}
            maxLength={maxLength}
          />
        ) : type === 'select' ? (
          <select
            {...shared}
            defaultValue={defaultValue}
            className={classNames(
              control,
              controlSizes.md,
              'min-h-(--dk-layout-control-height-lg) appearance-none pe-2xl forced-colors:appearance-auto',
            )}
          >
            {emptyLabel === null ? null : <option value="">{emptyLabel}</option>}
            {options.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        ) : (
          <input
            {...shared}
            ref={ref}
            className={classNames(
              control,
              compact ? controlSizes.sm : controlSizes.md,
              !compact && 'min-h-(--dk-layout-control-height-lg)',
              trailing ? 'pe-3xl' : undefined,
            )}
            type={type}
            autoComplete={autocomplete}
            // The floating label rests on a blank placeholder; a compact field shows its own.
            placeholder={compact ? placeholder : ' '}
            defaultValue={defaultValue}
            inputMode={inputMode}
            maxLength={maxLength}
          />
        )}
        <label className={compact ? 'sr-only' : floatingLabel} htmlFor={id}>
          {label}
          {!required && <span className="dk-field__optional ms-2xs font-regular">(optional)</span>}
        </label>
        {trailing && type !== 'select' && type !== 'textarea' ? (
          <div className="dk-field__trailing col-start-1 row-start-1 me-2xs flex self-center justify-self-end">
            {trailing}
          </div>
        ) : null}
        {type === 'select' && (
          <Icon
            name="chevron-down"
            className="dk-field__select-arrow pointer-events-none col-start-1 row-start-1 me-md self-center justify-self-end text-surface-accent peer-disabled:text-disabled-text forced-colors:hidden"
          />
        )}
      </div>
      {hint && (
        <p className="dk-field__hint px-md text-body-sm text-surface-muted" id={hintId}>
          {hint}
        </p>
      )}
      {error && (
        <p className="dk-field__error px-md text-body-sm text-surface-error" id={errorId}>
          {error}
        </p>
      )}
    </div>
  );
}

Best practices

  • Use a visible label and a unique name for every control.
  • Connect hints and errors to the field; do not rely on color alone.
  • Validate submitted values on the server as well as in the browser.