# Textarea

A text area that opens at three lines and grows to eight as you write, with a counter that turns orange near its limit; its reason kind is where saying no to an agent comes with a why.

Tier: free. Type: component. Category: inputs. Tags: form, approval.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/textarea.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/textarea.tsx`.

## Preview

Live preview: https://pixilui.com/components/textarea

Knobs:

- `kind`: `area`, `reason`

Signature: The box opens at three lines and grows a line at a time as you write, and the counter turns orange at 90% of the limit.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/textarea.tsx, quiet https://pixilui.com/r/standalone/textarea.quiet.tsx.

## Code

`components/pixilui/textarea.tsx`

```tsx
"use client";

/*
  The textarea and the reason field, locked 1 Dec 2026 (design/explorations/components/locked/inputs, B8).
  The frame and the rule are the Field's (../field/field); the look is foundation.css section 8.

  Height    opens at three lines and grows with the text to eight, then scrolls (the limits are the
            foundation's --pixilui-field-area-lines and -max). Enter is a new line.
  Counter   with maxLength and counter, the hint counts what is typed and turns orange at 90%.
  Reason    kind="reason" is the reason for a no: the same well, and addReason() drops a ready reason in
            as if typed, after what is already there, so a chip can fill it with one tap.
  Typing    native: nothing animates on keys.
*/

import {
  forwardRef,
  useCallback,
  useImperativeHandle,
  useLayoutEffect,
  useRef,
  useState,
  type ChangeEvent,
  type ComponentPropsWithoutRef,
  type FocusEvent,
  type ReactNode,
} from "react";
import { Field, FieldControl, FieldTextarea, setFieldValue, useFieldValidation, type FieldValidate } from "./field";

export type TextareaHandle = HTMLTextAreaElement & {
  /** Puts a ready reason in the field after what is there, as if typed (onChange runs), and focuses it. */
  addReason: (reason: string) => void;
};

export type TextareaProps = Omit<ComponentPropsWithoutRef<"textarea">, "size"> & {
  /** The label above the field. */
  label?: ReactNode;
  /** Right of the label: "Optional". A counter takes its place when counter is on. */
  hint?: ReactNode;
  /** Show the count of what is typed against maxLength in the hint's place. */
  counter?: boolean;
  /** How the counter reads; "118 / 600" by default. */
  formatCount?: (value: number, max?: number) => string;
  /** Help under the field. */
  description?: ReactNode;
  /** An error from outside, in plain words. */
  error?: ReactNode;
  /** The field's rule, run on blur: return what is wrong, nothing, or a promise. */
  validate?: FieldValidate;
  /** area is a textarea; reason is the reason for a no, with addReason on its ref. */
  kind?: "area" | "reason";
  /** Classes for the field. Native attributes and the ref go to the textarea. */
  className?: string;
};

/** A textarea that opens at three lines and grows to eight, with a counter, and the reason field for a no. */
export const Textarea = forwardRef<TextareaHandle, TextareaProps>(function Textarea(
  { label, hint, counter, formatCount, description, error, validate, kind = "area", className, value, defaultValue, onChange, onBlur, id, maxLength, ...props },
  ref,
) {
  const area = useRef<HTMLTextAreaElement | null>(null);
  const [inner, setInner] = useState(String(defaultValue ?? ""));
  const current = value != null ? String(value) : inner;
  const rule = useFieldValidation(validate);

  const grow = useCallback(() => {
    const el = area.current;
    if (!el) return;
    el.style.height = "auto";
    el.style.height = `${el.scrollHeight}px`;
  }, []);
  useLayoutEffect(grow, [current, grow]);

  useImperativeHandle(
    ref,
    () =>
      Object.assign(area.current!, {
        addReason: (reason: string) => {
          const el = area.current!;
          const now = el.value.trim();
          setFieldValue(el, now ? `${now} ${reason}` : reason);
          el.focus();
        },
      }),
    [],
  );

  return (
    <Field
      className={className}
      label={label}
      hint={hint}
      count={counter ? { value: [...current].length, max: maxLength, format: formatCount } : undefined}
      description={description}
      error={error ?? rule.invalid ?? undefined}
      reserveMessage={!!validate}
      kind={kind}
      check={rule.check}
      filled={current.length > 0}
      shake={rule.shake}
      inputId={id}
    >
      <FieldControl>
        <FieldTextarea
          ref={area}
          value={value}
          defaultValue={defaultValue}
          maxLength={maxLength}
          onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
            if (value == null) setInner(event.target.value);
            rule.reset();
            onChange?.(event);
          }}
          onBlur={(event: FocusEvent<HTMLTextAreaElement>) => {
            onBlur?.(event);
            if (validate && (event.currentTarget.value || rule.invalid)) rule.run(event.currentTarget.value);
          }}
          {...props}
        />
      </FieldControl>
    </Field>
  );
});
```

## Usage

When to use:

- Instructions, notes and descriptions.
- The reason for a denial (kind="reason"), so the agent can tell the customer.

When not to use:

- One line: use Input.
- A chat composer: use the composer.

```tsx
import { Textarea } from "@/components/pixilui/textarea";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  kind: ["area", "reason"],
} as const;

/** An agent's instructions, or the reason for a denial. */
export default function TextareaDemo({ kind = "area" }: KnobValues<typeof knobs>) {
  return (
    <div className="w-full max-w-md">
      {kind === "reason" ? (
        <Textarea key="reason" kind="reason" label="Reason" counter maxLength={280} placeholder="Tell the agent why, so it can tell the customer" />
      ) : (
        <Textarea
          key="area"
          label="Instructions"
          counter
          maxLength={600}
          placeholder="Tell the agent how to work"
          defaultValue="Answer billing questions first. Offer a refund only when the charge is a duplicate, and ask before anything over $200."
        />
      )}
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` |  | Classes for the field. Native attributes and the ref go to the textarea. |
| `label` | `ReactNode` |  | The label above the field. |
| `hint` | `ReactNode` |  | Right of the label: "Optional". A counter takes its place when counter is on. |
| `counter` | `boolean` |  | Show the count of what is typed against maxLength in the hint's place. |
| `formatCount` | `(value: number, max?: number) => string` |  | How the counter reads; "118 / 600" by default. |
| `description` | `ReactNode` |  | Help under the field. |
| `error` | `ReactNode` |  | An error from outside, in plain words. |
| `validate` | `FieldValidate` |  | The field's rule, run on blur: return what is wrong, nothing, or a promise. |
| `kind` | `"area" \| "reason"` | `"area"` | area is a textarea; reason is the reason for a no, with addReason on its ref. |

Also accepts every native `<textarea>` attribute except `size`, and a ref to it.

## Keyboard

- `Tab`: Moves into the field.
- `Enter`: Starts a new line.

## Accessibility

- The label names the input (aria-labelledby) and the help or error describes it (aria-describedby), so a hint or a counter is never read as its name.
- An error sets aria-invalid and says what is wrong in words; the color is never the only sign.
- The counter is in the label row and is not read as the name.

## Motion

- It grows with its text up to eight lines, then scrolls; nothing animates on keys.
- An error shakes the well once. Reduced motion: no shake.

## Responsive

- Fills its container's width; the label row and the message wrap.

## Performance

- Native typing: nothing renders per key beyond the value; the look is CSS in the foundation (section 8).

## Notes for AI

- <Textarea label="Instructions" counter maxLength={600} />; kind="reason" for a denial's reason.
- formatCount changes the counter's words ("42 / 600" by default).

## Related

- [Input](https://pixilui.com/components/input/markdown): A text field with its label, help and error, a unit or icon on either side, and a rule that checks on blur and Enter and says what's wrong in plain words.
- [Field](https://pixilui.com/components/field/markdown): The frame every PixilUI field shares: a label row, a well with a rim you can see on white, and a message that says what's wrong in plain words, wired for screen readers.
