Skip to content

Textarea

A flexible multi-line text input with character counting and validation states. Designed for collecting longer form content with accessibility in mind.

0

Installation

Add Text Area to your project with the CK-UI CLI. It copies the source into your project, so the code is yours to change.

Terminal
npx ck-ui-cli@latest add textarea
Adds
Textarea.tsxField.tsxLabel.tsxto your CK-UI folder (src/components/ck-ui by default)
Installs
@radix-ui/react-label@radix-ui/react-slotif your project does not have them yet

First time with CK-UI in this project? Run npx ck-ui-cli@latest init once before adding components. The installation guide explains what it sets up.

Manual installationInstall the packages and copy the files yourself.

Install the following dependencies

Run these commands in your terminal to install the required packages

Terminal
npm install @radix-ui/react-slot @radix-ui/react-label

Add the Field component

Textarea imports ./Field, so add this file next to it

/components/ui/Field.tsx
"use client";

import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cn } from "@/lib/utils";
import * as Label from "./Label";

/*
 * Field wires a label, description and message to one form control:
 *   Field.Label        → <label for={controlId}>
 *   Field.Description  → referenced by aria-describedby
 *   Field.Message      → referenced by aria-describedby (error text when invalid)
 *   invalid / required / disabled → aria-invalid, required/aria-required, disabled on the control
 * Controls (Input, Textarea, Select, Checkbox, Switch, Radio) read the context through
 * useFieldControlProps. It is plain React state: it works with native forms and form libraries.
 */

type FieldContextValue = {
    controlId: string;
    labelId: string;
    descriptionId: string;
    messageId: string;
    invalid: boolean;
    required: boolean;
    disabled: boolean;
    hasDescription: boolean;
    hasMessage: boolean;
    setHasDescription: (value: boolean) => void;
    setHasMessage: (value: boolean) => void;
};

const FieldContext = React.createContext<FieldContextValue | null>(null);

export function useField() {
    return React.useContext(FieldContext);
}

/**
 * Provided by Fieldset.Root. A native <fieldset disabled> already disables the controls inside it;
 * this lets each Field.Root reflect that state (label styling, `disabled` on the control).
 */
export const FieldsetContext = React.createContext<{ disabled: boolean } | null>(null);

export interface FieldRootProps extends React.HTMLAttributes<HTMLDivElement> {
    /** Id for the control; generated when omitted. */
    id?: string;
    invalid?: boolean;
    required?: boolean;
    disabled?: boolean;
}

const Root = React.forwardRef<HTMLDivElement, FieldRootProps>(({ id, invalid = false, required = false, disabled: disabledProp = false, className, children, ...props }, ref) => {
    const fieldset = React.useContext(FieldsetContext);
    const disabled = disabledProp || Boolean(fieldset?.disabled);
    const generatedId = React.useId();
    const controlId = id ?? `field-${generatedId}`;
    const [hasDescription, setHasDescription] = React.useState(false);
    const [hasMessage, setHasMessage] = React.useState(false);

    const value = React.useMemo<FieldContextValue>(
        () => ({
            controlId,
            labelId: `${controlId}-label`,
            descriptionId: `${controlId}-description`,
            messageId: `${controlId}-message`,
            invalid,
            required,
            disabled,
            hasDescription,
            hasMessage,
            setHasDescription,
            setHasMessage,
        }),
        [controlId, invalid, required, disabled, hasDescription, hasMessage]
    );

    return (
        <FieldContext.Provider value={value}>
            <div
                ref={ref}
                className={cn("flex flex-col gap-1.5", className)}
                data-invalid={invalid || undefined}
                data-disabled={disabled || undefined}
                {...props}
            >
                {children}
            </div>
        </FieldContext.Provider>
    );
});
Root.displayName = "Field.Root";

type FieldLabelProps = React.ComponentPropsWithoutRef<typeof Label.Root>;

const FieldLabel = React.forwardRef<React.ElementRef<typeof Label.Root>, FieldLabelProps>(({ children, ...props }, ref) => {
    const field = useField();

    return (
        <Label.Root ref={ref} id={field?.labelId} htmlFor={field?.controlId} disabled={field?.disabled} {...props}>
            {children}
            {field?.required && <Label.Asterisk />}
        </Label.Root>
    );
});
FieldLabel.displayName = "Field.Label";

const Description = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLParagraphElement>>(({ className, ...props }, ref) => {
    const field = useField();
    const setHasDescription = field?.setHasDescription;

    React.useEffect(() => {
        if (!setHasDescription) return;
        setHasDescription(true);
        return () => setHasDescription(false);
    }, [setHasDescription]);

    return <p ref={ref} id={field?.descriptionId} className={cn("size-p-xs text-muted-foreground", className)} {...props} />;
});
Description.displayName = "Field.Description";

export interface FieldMessageProps extends React.HTMLAttributes<HTMLParagraphElement> {
    /** Only render while the field is invalid (default true). */
    showWhenValid?: boolean;
}

const Message = React.forwardRef<HTMLParagraphElement, FieldMessageProps>(({ className, showWhenValid = false, children, ...props }, ref) => {
    const field = useField();
    const visible = Boolean(children) && (showWhenValid || !field || field.invalid);
    const setHasMessage = field?.setHasMessage;

    React.useEffect(() => {
        if (!setHasMessage || !visible) return;
        setHasMessage(true);
        return () => setHasMessage(false);
    }, [setHasMessage, visible]);

    if (!visible) return null;

    return (
        <p
            ref={ref}
            id={field?.messageId}
            aria-live="polite"
            className={cn("size-p-xs", field?.invalid ? "text-destructive-strong" : "text-muted-foreground", className)}
            {...props}
        >
            {children}
        </p>
    );
});
Message.displayName = "Field.Message";

type ControlAttributes = {
    id?: string;
    "aria-describedby"?: string;
    "aria-invalid"?: React.AriaAttributes["aria-invalid"];
    "aria-required"?: React.AriaAttributes["aria-required"];
    required?: boolean;
    disabled?: boolean;
};

/**
 * Merges Field context into a control's props. Explicit props win; describedby ids are combined.
 */
export function useFieldControlProps<P extends ControlAttributes>(props: P, options: { invalid?: boolean } = {}): P & ControlAttributes {
    const field = useField();
    const invalid = Boolean(options.invalid || field?.invalid || props["aria-invalid"] === true || props["aria-invalid"] === "true");

    const describedBy = [props["aria-describedby"], field?.hasDescription ? field.descriptionId : undefined, field?.hasMessage ? field.messageId : undefined]
        .filter(Boolean)
        .join(" ");

    return {
        ...props,
        id: props.id ?? field?.controlId,
        "aria-describedby": describedBy || undefined,
        "aria-invalid": invalid || undefined,
        required: props.required ?? (field?.required || undefined),
        disabled: props.disabled ?? (field?.disabled || undefined),
    };
}

/** Applies Field wiring to any custom control element (single child). */
const Control = React.forwardRef<HTMLElement, React.HTMLAttributes<HTMLElement> & ControlAttributes>((props, ref) => {
    const controlProps = useFieldControlProps(props);
    return <Slot ref={ref} {...controlProps} />;
});
Control.displayName = "Field.Control";

export { Root, FieldLabel as Label, Description, Message, Control };

Add the Label component

Textarea imports ./Label, so add this file next to it

/components/ui/Label.tsx
"use client";

import * as React from "react";
import * as LabelPrimitive from "@radix-ui/react-label";
import { cn } from "@/lib/utils";

export interface LabelRootProps extends React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> {
    /** Dims the label. The control itself must also be disabled. */
    disabled?: boolean;
}

const Root = React.forwardRef<React.ElementRef<typeof LabelPrimitive.Root>, LabelRootProps>(({ className, disabled, ...props }, ref) => {
    return (
        <LabelPrimitive.Root
            ref={ref}
            data-disabled={disabled || undefined}
            className={cn(
                "group flex cursor-pointer items-center gap-px size-p-sm text-foreground",
                "data-[disabled]:pointer-events-none data-[disabled]:text-muted-foreground/60",
                className
            )}
            {...props}
        />
    );
});
Root.displayName = "Label.Root";

// Visual required marker. Screen readers get "required" from the control (required / aria-required).
const Asterisk = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>(({ className, children, ...props }, ref) => (
    <span ref={ref} aria-hidden="true" className={cn("text-primary-strong group-data-[disabled]:text-muted-foreground/60", className)} {...props}>
        {children || "*"}
    </span>
));
Asterisk.displayName = "Label.Asterisk";

const Sub = React.forwardRef<HTMLSpanElement, React.HTMLAttributes<HTMLSpanElement>>(({ className, ...props }, ref) => (
    <span ref={ref} className={cn("size-p-xs text-muted-foreground group-data-[disabled]:text-muted-foreground/60", className)} {...props} />
));
Sub.displayName = "Label.Sub";

export { Root, Asterisk, Sub };

Create or update your Textarea component

Copy this code to create your Textarea component

/components/ui/Textarea.tsx
"use client";

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

const MIN_HEIGHT = 82;

export interface TextareaRootProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
    /** Error state: destructive border and aria-invalid. Also taken from Field.Root. */
    invalid?: boolean;
    /** @deprecated Use `invalid`. */
    error?: boolean;
    /** Called with the new text on every change, in addition to the native `onChange` event handler. */
    onValueChange?: (value: string) => void;
    /** Show the drag handle for resizing (default true). */
    resizable?: boolean;
    /** Extra content shown in the bottom-right corner, e.g. <Textarea.CharCounter max={200} />. */
    children?: React.ReactNode;
    /** Class for the outer wrapper; `className` styles the <textarea> itself. */
    wrapperClassName?: string;
}

interface TextareaContextValue {
    length: number;
    counterId: string;
    setHasCounter: (value: boolean) => void;
}

const TextareaContext = React.createContext<TextareaContextValue | null>(null);

const TextareaRoot = React.forwardRef<HTMLTextAreaElement, TextareaRootProps>(
    (
        { className, wrapperClassName, invalid, error, children, style, value, defaultValue, onChange, onValueChange, resizable = true, ...props },
        forwardedRef
    ) => {
        const isControlled = value !== undefined;
        const [internalValue, setInternalValue] = React.useState(() => String(defaultValue ?? ""));
        const currentValue = isControlled ? String(value ?? "") : internalValue;
        const [height, setHeight] = React.useState<number | null>(null);
        const [hasCounter, setHasCounter] = React.useState(false);
        const counterId = `${React.useId()}-counter`;
        const resizeStart = React.useRef<{ y: number; height: number } | null>(null);
        const textareaRef = React.useRef<HTMLTextAreaElement | null>(null);

        const controlProps = useFieldControlProps(
            {
                ...props,
                "aria-describedby": [props["aria-describedby"], hasCounter ? counterId : undefined].filter(Boolean).join(" ") || undefined,
            },
            { invalid: invalid ?? error }
        );
        const disabled = Boolean(controlProps.disabled);

        const setRefs = (node: HTMLTextAreaElement | null) => {
            textareaRef.current = node;
            if (typeof forwardedRef === "function") forwardedRef(node);
            else if (forwardedRef) forwardedRef.current = node;
        };

        const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
            if (!isControlled) setInternalValue(event.target.value);
            onChange?.(event);
            onValueChange?.(event.target.value);
        };

        // Pointer events cover mouse, pen and touch. The handle is decorative for assistive tech.
        const handlePointerDown = (event: React.PointerEvent<HTMLSpanElement>) => {
            if (disabled || !textareaRef.current) return;
            event.preventDefault();
            event.currentTarget.setPointerCapture(event.pointerId);
            resizeStart.current = { y: event.clientY, height: textareaRef.current.offsetHeight };
        };

        const handlePointerMove = (event: React.PointerEvent<HTMLSpanElement>) => {
            if (!resizeStart.current) return;
            setHeight(Math.max(MIN_HEIGHT, resizeStart.current.height + event.clientY - resizeStart.current.y));
        };

        const handlePointerUp = (event: React.PointerEvent<HTMLSpanElement>) => {
            resizeStart.current = null;
            if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
        };

        return (
            <TextareaContext.Provider value={{ length: currentValue.length, counterId, setHasCounter }}>
                <div data-disabled={disabled || undefined} className={cn("group/textarea relative flex w-full flex-col size-p-sm", wrapperClassName)}>
                    <textarea
                        ref={setRefs}
                        value={currentValue}
                        onChange={handleChange}
                        style={{ ...(height !== null ? { height } : null), ...style }}
                        className={cn(
                            "block w-full resize-none rounded-xl border bg-transparent px-3 py-2.5 pb-8 size-p-sm text-foreground",
                            "min-h-[82px] transition-colors duration-base ease-standard",
                            "placeholder:text-muted-foreground",
                            // Field focus. The halo colour and ring-0 are focus variants so they beat the forms plugin's
                            // `textarea:focus` base rule (its transparent outline and blue 1px ring).
                            "field-focus focus:ring-0",
                            controlProps["aria-invalid"]
                                ? "border-destructive focus:outline-destructive/25 hover:bg-destructive-subtle focus:border-destructive focus:hover:bg-transparent"
                                : "border-input focus:outline-accent hover:bg-muted focus:border-foreground focus:hover:bg-transparent",
                            "disabled:cursor-not-allowed disabled:border-transparent disabled:bg-muted disabled:text-muted-foreground disabled:placeholder:text-muted-foreground/60",
                            className
                        )}
                        {...controlProps}
                    />

                    <div className="absolute bottom-2 right-2 flex items-center gap-1.5">
                        {children}
                        {resizable && (
                            <span
                                aria-hidden="true"
                                onPointerDown={handlePointerDown}
                                onPointerMove={handlePointerMove}
                                onPointerUp={handlePointerUp}
                                onPointerCancel={handlePointerUp}
                                className="cursor-se-resize touch-none text-muted-foreground/60 group-data-[disabled]/textarea:pointer-events-none"
                            >
                                <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                                    <path d="M9.11111 2L2 9.11111M10 6.44444L6.44444 10" stroke="currentColor" strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                            </span>
                        )}
                    </div>
                </div>
            </TextareaContext.Provider>
        );
    }
);
TextareaRoot.displayName = "Textarea.Root";

export interface TextareaCharCounterProps extends React.HTMLAttributes<HTMLSpanElement> {
    /** Character limit. Without it the counter shows the current length only. */
    max?: number;
    /** Override the counted length (defaults to the textarea's current value length). */
    current?: number;
}

const CharCounter = React.forwardRef<HTMLSpanElement, TextareaCharCounterProps>(({ current, max, className, ...props }, ref) => {
    const context = React.useContext(TextareaContext);
    const count = current ?? context?.length ?? 0;
    const overLimit = max !== undefined && count > max;
    const setHasCounter = context?.setHasCounter;

    React.useEffect(() => {
        if (!setHasCounter) return;
        setHasCounter(true);
        return () => setHasCounter(false);
    }, [setHasCounter]);

    return (
        <span
            ref={ref}
            id={context?.counterId}
            className={cn(
                "size-subheading-2xs tabular-nums transition-colors",
                // Full muted-foreground: the faded /70 shade measured 2.92:1 on white.
                overLimit ? "text-destructive-strong" : "text-muted-foreground",
                "group-data-[disabled]/textarea:text-muted-foreground/40",
                className
            )}
            {...props}
        >
            {max !== undefined ? `${count}/${max}` : count}
            {max !== undefined && <span className="sr-only"> characters used</span>}
        </span>
    );
});
CharCounter.displayName = "Textarea.CharCounter";

export { TextareaRoot as Root, CharCounter };

Test Your Component

  • 1. Add the component to a test page
  • 2. Check all props and variants work as expected
  • 3. Verify responsive behavior
  • 4. Test with different content/data
  • 5. Ensure accessibility features work correctly

Character Counter

Track and limit the number of characters with a built-in counter component.

0/200 characters used

Disabled State

Textareas can be disabled to prevent user interaction.

0/200 characters used

Error State

Display error states to indicate validation issues or input errors.

0/200 characters used

Full Example

A complete example with label, textarea, character counter, and hint text.

0

This is a hint text to help user.

API Reference

The Textarea component is a custom implementation built with native HTML textarea elements and enhanced with additional features like character counting and custom resizing.

Textarea.Root

The main textarea component that users interact with.

PropTypeDefaultDescription
invalid"boolean""false"

Error styling and aria-invalid. Also set automatically inside Field.Root invalid. (The old error prop still works but is deprecated.)

value"string""undefined"

The controlled value of the textarea.

defaultValue"string""undefined"

The initial value when uncontrolled.

onChange"(event: React.ChangeEvent<HTMLTextAreaElement>) => void""undefined"

Native change event handler, compatible with form libraries.

onValueChange"(value: string) => void""undefined"

Called with the new text on every change.

resizable"boolean""true"

Shows the drag handle for resizing (mouse, touch and pen).

disabled"boolean""false"

Prevents interaction. Also taken from Field.Root disabled.

className"string""undefined"

Classes for the <textarea> element.

wrapperClassName"string""undefined"

Classes for the outer wrapper.

Textarea.CharCounter

A component that displays the current character count and optional maximum limit.

PropTypeDefaultDescription
current"number""undefined"

Override the counted length. By default the counter reads the textarea value.

max"number""undefined"

The maximum character count, shown as current/max. Without it only the current count is shown.

className"string""undefined"

Additional CSS classes to apply to the character counter.

Used in these blocks

Block families with at least one block built on this component. Each page previews its blocks and lists the components and packages they use.