Inputs & Forms

Textarea

An auto-growing textarea using field-sizing: content with a JS fallback, plus a tabular-nums character count that tightens color as the limit approaches.

Install

npx shadcn@latest add @paragon/textarea

textarea.tsx

"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export interface TextareaProps extends React.ComponentProps<"textarea"> {
  /** Visible label, wired via htmlFor. */
  label?: string;
  /** Helper text below the field. Hidden while an error is shown. */
  hint?: string;
  /** Error message. Turns the field red. */
  error?: string;
  /** Grow with content. Uses `field-sizing: content` with a JS fallback. */
  autoGrow?: boolean;
  /** Show the character count. Defaults to true when maxLength is set. */
  showCount?: boolean;
}

/**
 * Auto-growing textarea. Prefers the native `field-sizing: content` and
 * falls back to a scrollHeight measure where unsupported. The character
 * count is tabular-nums and tightens color as the limit approaches.
 */
export function Textarea({
  label,
  hint,
  error,
  autoGrow = true,
  showCount,
  maxLength,
  className,
  id: idProp,
  rows = 3,
  onChange,
  disabled,
  "aria-describedby": ariaDescribedBy,
  ...props
}: TextareaProps) {
  const autoId = React.useId();
  const id = idProp ?? autoId;
  const messageId = `${id}-message`;
  const ref = React.useRef<HTMLTextAreaElement>(null);

  const initial =
    props.value ?? props.defaultValue ?? "";
  const [count, setCount] = React.useState(String(initial).length);
  const length =
    props.value !== undefined ? String(props.value).length : count;

  const [nativeSizing, setNativeSizing] = React.useState(true);
  React.useEffect(() => {
    setNativeSizing(
      typeof CSS !== "undefined" && CSS.supports("field-sizing", "content"),
    );
  }, []);

  const resize = React.useCallback(() => {
    const el = ref.current;
    if (!el) return;
    el.style.height = "auto";
    el.style.height = `${el.scrollHeight + 2}px`; // +2 for the border
  }, []);

  // JS fallback: measure on mount and whenever the (controlled) value changes.
  React.useLayoutEffect(() => {
    if (autoGrow && !nativeSizing) resize();
  }, [autoGrow, nativeSizing, resize, props.value]);

  const showsCount = (showCount ?? maxLength !== undefined) && !disabled;
  const ratio = maxLength ? length / maxLength : 0;
  const invalid = Boolean(error);
  const message = error ?? hint;

  return (
    <div className="w-full">
      {label && (
        <label
          htmlFor={id}
          className="mb-1.5 block text-sm font-medium text-foreground"
        >
          {label}
        </label>
      )}
      <textarea
        ref={ref}
        id={id}
        rows={rows}
        maxLength={maxLength}
        disabled={disabled}
        aria-invalid={invalid || undefined}
        aria-describedby={
          cn(message ? messageId : undefined, ariaDescribedBy) || undefined
        }
        onChange={(event) => {
          if (props.value === undefined) setCount(event.target.value.length);
          if (autoGrow && !nativeSizing) resize();
          onChange?.(event);
        }}
        className={cn(
          "w-full min-w-0 resize-none rounded-lg border border-input bg-transparent px-3 py-2 text-sm text-foreground",
          "transition-[border-color,box-shadow] duration-150 ease-out",
          "placeholder:text-muted-foreground",
          "outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/25",
          "disabled:cursor-not-allowed disabled:opacity-50",
          invalid &&
            "border-destructive focus-visible:border-destructive focus-visible:ring-destructive/20",
          className,
        )}
        style={
          autoGrow
            ? ({ fieldSizing: "content" } as React.CSSProperties)
            : undefined
        }
        {...props}
      />
      {(message || showsCount) && (
        <div className="mt-1 flex items-baseline justify-between gap-4">
          <p
            id={messageId}
            role={invalid ? "alert" : undefined}
            className={cn(
              "min-w-0 text-[13px]",
              invalid ? "text-destructive" : "text-muted-foreground",
            )}
          >
            {message}
          </p>
          {showsCount && (
            <span
              aria-hidden
              className={cn(
                "shrink-0 text-xs tabular-nums transition-colors duration-150 ease-out",
                ratio >= 1
                  ? "text-destructive"
                  : ratio >= 0.85
                    ? "text-amber-600 dark:text-amber-400"
                    : "text-muted-foreground/70",
              )}
            >
              {maxLength !== undefined ? `${length}/${maxLength}` : length}
            </span>
          )}
        </div>
      )}
    </div>
  );
}