Text field

A labelled text input with hint text, an error message wired through aria-describedby and aria-invalid, an optional leading icon or prefix, and a trailing slot for units, keyboard hints or a small TextFieldButton (for example show password). Three sizes, a disabled state, forwarded ref, and clicks on the padding focus the input.

Forms & inputsComponentTailwind v4

Source

"use client";

import {
  forwardRef, useCallback, useId, useRef,
  type ButtonHTMLAttributes, type InputHTMLAttributes, type MouseEvent, type ReactNode,
} from "react";
import { CircleAlert } from "lucide-react";
import { cn } from "@/lib/utils";

export type TextFieldSize = "sm" | "md" | "lg";

export interface TextFieldProps extends Omit<InputHTMLAttributes<HTMLInputElement>, "size"> {
  label: ReactNode;
  /** Keeps the label for screen readers but hides it visually. */
  hideLabel?: boolean;
  /** Help text under the field. Replaced by the error while one is shown. */
  hint?: ReactNode;
  /** Marks the field invalid (aria-invalid) and shows the message under it. */
  error?: ReactNode;
  /** An icon or short text before the value, such as a search icon or "$". */
  leadingIcon?: ReactNode;
  /** Anything after the value: a unit, a keyboard hint or a TextFieldButton. */
  trailing?: ReactNode;
  size?: TextFieldSize;
  containerClassName?: string;
}

const boxSizes: Record<TextFieldSize, string> = {
  sm: "h-8 gap-1.5 px-2.5 text-[13px] [&_svg]:size-3.5",
  md: "h-9 gap-2 px-3 text-sm [&_svg]:size-4",
  lg: "h-11 gap-2.5 px-3.5 text-[15px] [&_svg]:size-[18px]",
};

export const TextField = forwardRef<HTMLInputElement, TextFieldProps>(function TextField(
  {
    label, hideLabel, hint, error, leadingIcon, trailing, size = "md", id, className, containerClassName,
    disabled, required, "aria-describedby": describedBy, ...props
  },
  ref,
) {
  const autoId = useId();
  const inputId = id ?? `${autoId}-input`;
  const hintId = `${autoId}-hint`;
  const errorId = `${autoId}-error`;
  const invalid = Boolean(error);
  const inputRef = useRef<HTMLInputElement | null>(null);

  const setRefs = useCallback((node: HTMLInputElement | null) => {
    inputRef.current = node;
    if (typeof ref === "function") ref(node);
    else if (ref) ref.current = node;
  }, [ref]);

  // Clicking the padding or the leading icon focuses the input, like one large hit area.
  function handleBoxMouseDown(event: MouseEvent<HTMLDivElement>) {
    const target = event.target as HTMLElement;
    if (disabled || target === inputRef.current || target.closest("button, a, input, select, textarea")) return;
    event.preventDefault();
    inputRef.current?.focus();
  }

  const described = [describedBy, invalid ? errorId : hint ? hintId : null].filter(Boolean).join(" ") || undefined;

  return (
    <div className={cn("flex min-w-0 flex-col gap-1.5", containerClassName)}>
      <label htmlFor={inputId} className={cn("w-fit text-sm font-medium text-foreground", hideLabel && "sr-only")}>
        {label}
        {required && <span aria-hidden="true" className="ml-0.5 text-muted-foreground">*</span>}
      </label>

      <div
        data-invalid={invalid || undefined}
        data-disabled={disabled || undefined}
        onMouseDown={handleBoxMouseDown}
        className={cn(
          "flex w-full cursor-text items-center rounded-md border border-input bg-background shadow-xs shadow-black/[0.03]",
          "transition-[border-color,box-shadow] duration-150 dark:bg-input/20",
          "has-[input:focus-visible]:border-ring has-[input:focus-visible]:ring-[3px] has-[input:focus-visible]:ring-ring/40",
          "data-[invalid]:border-destructive/70 data-[invalid]:has-[input:focus-visible]:border-destructive",
          "data-[invalid]:has-[input:focus-visible]:ring-destructive/20",
          "data-[disabled]:cursor-not-allowed data-[disabled]:bg-muted/60 data-[disabled]:opacity-60",
          boxSizes[size],
        )}
      >
        {leadingIcon && (
          <span aria-hidden="true" className="flex shrink-0 select-none items-center text-muted-foreground [&_svg]:shrink-0">
            {leadingIcon}
          </span>
        )}
        <input
          ref={setRefs}
          id={inputId}
          disabled={disabled}
          required={required}
          aria-invalid={invalid || undefined}
          aria-describedby={described}
          className={cn(
            "h-full w-full min-w-0 flex-1 bg-transparent text-foreground outline-hidden placeholder:text-muted-foreground/70",
            "disabled:cursor-not-allowed [&::-webkit-search-cancel-button]:hidden",
            className,
          )}
          {...props}
        />
        {trailing && (
          <span className="-mr-1 flex shrink-0 items-center gap-1 text-muted-foreground [&_svg]:shrink-0">{trailing}</span>
        )}
      </div>

      {invalid ? (
        <p id={errorId} className="flex items-start gap-1.5 text-[13px] leading-5 text-destructive">
          <CircleAlert aria-hidden="true" className="mt-[3px] size-3.5 shrink-0" />
          <span>{error}</span>
        </p>
      ) : hint ? (
        <p id={hintId} className="text-[13px] leading-5 text-muted-foreground">{hint}</p>
      ) : null}
    </div>
  );
});

/** A small icon button sized for the TextField trailing slot, such as show password or clear. Give it an aria-label. */
export const TextFieldButton = forwardRef<HTMLButtonElement, ButtonHTMLAttributes<HTMLButtonElement>>(function TextFieldButton(
  { className, type = "button", ...props },
  ref,
) {
  return (
    <button
      ref={ref}
      type={type}
      className={cn(
        "inline-flex size-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground outline-hidden",
        "transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50",
        "disabled:pointer-events-none disabled:opacity-50",
        className,
      )}
      {...props}
    />
  );
});