Menu

Components

Textarea

A field for longer, multi-line text, with a label, help text and an error message. Built on react-aria-components.

Introduction

Use Textarea when the answer is more than a line: a message, a comment, a bio. It is a text field that keeps line breaks, with a label, help text and an error message that match the other fields.

  • rows sets how tall it is, and the user can drag the corner to change that.
  • isAutoResize makes it grow as they type, so there is no inner scrollbar, up to maxRows.
  • A character limit with maxLength, and a counter with showCount.
  • Works in a form: give it a name and the text is submitted with it.

For a single line, use Text Field.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/textarea-styles.tsShow code
import { tv } from "tailwind-variants";

// The textarea itself carries the border, the background and the focus ring.
// The state of the field around it (invalid, disabled) comes through the
// `group/textarea` name, from data attributes react-aria sets on the root.
export const textareaStyles = tv({
  base: [
    "block w-full rounded-md text-fg outline-none transition-colors placeholder:text-muted-fg",
    "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-bg",
    "group-data-invalid/textarea:border-danger",
    "group-data-disabled/textarea:cursor-not-allowed group-data-disabled/textarea:opacity-50",
    "read-only:cursor-default",
  ],
  variants: {
    variant: {
      outline: "border bg-transparent",
      secondary: "bg-secondary text-secondary-fg",
      ghost: "bg-transparent hover:bg-muted focus-visible:bg-muted",
    },
    size: {
      sm: "px-2.5 py-1.5 text-sm",
      md: "px-3 py-2 text-sm",
      lg: "px-3.5 py-2.5 text-base",
    },
    // The little handle in the corner. Auto-resize turns it off, since the
    // height follows the text.
    resize: {
      none: "resize-none",
      vertical: "resize-y",
      horizontal: "resize-x",
      both: "resize",
    },
  },
  defaultVariants: { variant: "outline", size: "md", resize: "vertical" },
});

2. Add the Textarea file

src/components/ui/textarea/textarea.tsxShow code
"use client";

import {
  type ReactNode,
  useCallback,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import {
  TextField as AriaTextField,
  type TextFieldProps as AriaTextFieldProps,
  FieldError,
  Label,
  Text,
  TextArea,
  type ValidationResult,
} from "react-aria-components";
import { cn } from "@/lib/cn";
import { textareaStyles } from "@/types/textarea-styles";

export interface TextareaProps
  extends Omit<
    AriaTextFieldProps,
    "children" | "className" | "type" | "inputMode" | "pattern"
  > {
  label?: ReactNode;
  /** Help text under the field. */
  description?: ReactNode;
  /** Shown when the field is invalid. A function receives the validation result. */
  errorMessage?: string | ((validation: ValidationResult) => string);
  placeholder?: string;
  /** Look of the field. */
  variant?: "outline" | "secondary" | "ghost";
  /** Size of the field. */
  size?: "sm" | "md" | "lg";
  /** How many lines are visible. With `isAutoResize` this is the minimum. */
  rows?: number;
  /** Grow and shrink with the text, so there is never a scrollbar (up to `maxRows`). */
  isAutoResize?: boolean;
  /** With `isAutoResize`: stop growing at this many lines and scroll instead. */
  maxRows?: number;
  /** The drag handle in the corner. Ignored with `isAutoResize`. */
  resize?: "none" | "vertical" | "horizontal" | "both";
  /** With `maxLength`: show how many characters are used, under the field. */
  showCount?: boolean;
  className?: string;
}

/**
 * A field for longer, multi-line text: a comment, a message, a bio. Built on
 * react-aria's TextField, so the label, description, error, keyboard support
 * and form submission (`name`) come from there.
 *
 * `rows` sets the visible lines and the user can drag the corner to resize it.
 * With `isAutoResize` it grows as they type instead, up to `maxRows`.
 *
 * @example
 * <Textarea label="Message" rows={4} placeholder="Tell us what you think" />
 */
export function Textarea({
  label,
  description,
  errorMessage,
  placeholder,
  variant,
  size = "md",
  rows = 3,
  isAutoResize = false,
  maxRows,
  resize = "vertical",
  showCount = false,
  className,
  value,
  defaultValue,
  onChange,
  maxLength,
  ...props
}: TextareaProps) {
  const ref = useRef<HTMLTextAreaElement>(null);
  // Mirrors the text so the counter and the auto-resize work whether the field
  // is controlled or not.
  const [typed, setTyped] = useState(defaultValue ?? "");
  const text = value ?? typed;

  const fit = useCallback(() => {
    const element = ref.current;
    if (!element || !isAutoResize) return;

    // Measure the real content height, then apply it, capped at maxRows.
    element.style.height = "auto";
    const style = getComputedStyle(element);
    const line =
      Number.parseFloat(style.lineHeight) ||
      Number.parseFloat(style.fontSize) * 1.5;
    const padding =
      Number.parseFloat(style.paddingTop) +
      Number.parseFloat(style.paddingBottom);
    const border =
      Number.parseFloat(style.borderTopWidth) +
      Number.parseFloat(style.borderBottomWidth);
    const max = maxRows
      ? line * maxRows + padding + border
      : Number.POSITIVE_INFINITY;
    const wanted = element.scrollHeight + border;

    element.style.height = `${Math.min(wanted, max)}px`;
    element.style.overflowY = wanted > max ? "auto" : "hidden";
  }, [isAutoResize, maxRows]);

  // Fit on every change of the text or the size, and when the width changes,
  // because narrower text wraps onto more lines.
  // biome-ignore lint/correctness/useExhaustiveDependencies: `text` and `size` are what should trigger a new measurement
  useLayoutEffect(fit, [fit, text, size]);
  useLayoutEffect(() => {
    const element = ref.current;
    if (!element || !isAutoResize) return;
    let width = element.clientWidth;
    const observer = new ResizeObserver(() => {
      if (element.clientWidth !== width) {
        width = element.clientWidth;
        fit();
      }
    });
    observer.observe(element);
    return () => {
      observer.disconnect();
      element.style.height = "";
      element.style.overflowY = "";
    };
  }, [fit, isAutoResize]);

  return (
    <AriaTextField
      {...props}
      value={value}
      defaultValue={defaultValue}
      maxLength={maxLength}
      onChange={(next) => {
        setTyped(next);
        onChange?.(next);
      }}
      className={cn("group/textarea flex w-full flex-col gap-1.5", className)}
    >
      {label ? (
        <Label className="text-sm font-medium group-data-required/textarea:after:ml-0.5 group-data-required/textarea:after:text-danger group-data-required/textarea:after:content-['*']">
          {label}
        </Label>
      ) : null}
      <TextArea
        ref={ref}
        rows={rows}
        placeholder={placeholder}
        className={textareaStyles({
          variant,
          size,
          resize: isAutoResize ? "none" : resize,
        })}
      />
      {description || (showCount && maxLength) ? (
        <div className="flex items-start justify-between gap-3 text-sm text-muted-fg">
          {description ? (
            <Text slot="description">{description}</Text>
          ) : (
            <span />
          )}
          {showCount && maxLength ? (
            <span aria-hidden="true" className="tabular-nums">
              {text.length}/{maxLength}
            </span>
          ) : null}
        </div>
      ) : null}
      <FieldError className="text-sm text-danger">{errorMessage}</FieldError>
    </AriaTextField>
  );
}

3. Use it

import { Textarea } from "@/components/ui/textarea/textarea";

Anatomy

A textarea is a bordered text box with a label and text under it.

<Textarea
  label="Message"
  description="We reply within a day."
  placeholder="Tell us what you think"
  rows={4}
  maxLength={200}
  showCount
/>
PartRendered asNotes
LabellabelNames the field. Clicking it focuses the text.
TextareatextareaWhere the text is typed. It has the border, and a drag handle in the corner unless it auto-resizes.
Description / countertext under the fieldHelp text on the left, and the character count on the right.
Errortext under the fieldShown while the field is invalid.

Without a label, give the field an aria-label so a screen reader can name it.

Examples

Live previews with code you can copy.

Usage

Label

Every field needs a name. Use label, or aria-label when the label is written elsewhere.

Description

Help text under the field.

We reply within a day.

Rows

How many lines are visible before the text scrolls.

Auto resize

With isAutoResize the height follows the text, so there is never a scrollbar. rows is then the minimum height.

Maximum rows

maxRows stops the growth. Past it, the text scrolls inside the box.

Resize handle

Which way the user can drag the corner. Set none to fix the size.

Character count

With maxLength, the field stops accepting text at the limit. showCount adds a counter under it.

A short line about you.

Uncontrolled

Let the field keep its own text. Start with defaultValue, and give it a name to read the value from a form.

Controlled

Keep the text in your own state with value and onChange, so you can read it, set it or clear it from outside.

26 characters, 5 words

Read only

The text can be selected and copied, but not changed. It is still submitted with a form.

Sizes

Variants

Disabled

Validation

Set isInvalid with an errorMessage. The field gets a red border and the message replaces the description.

Write at least 20 characters.
Write at least 20 characters.

Component API

Textarea takes the props below, plus most of what the react-aria TextField accepts.

PropTypeDefault
labelReactNode-
descriptionReactNode-
errorMessagestring | (validation) => string-
placeholderstring-
valuestring-
defaultValuestring""
onChange(value: string) => void-
rowsnumber3
isAutoResizebooleanfalse
maxRowsnumber-
resize"none" | "vertical" | "horizontal" | "both""vertical"
maxLengthnumber-
showCountbooleanfalse
namestring-
variant"outline" | "secondary" | "ghost""outline"
size"sm" | "md" | "lg""md"
autoFocusbooleanfalse
isDisabledbooleanfalse
isReadOnlybooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no label)