Textarea
An auto-growing React textarea built on shadcn/ui: the drop-in Textarea sizes itself to its content with a soft focus ring and clear invalid state — plus Motion blocks for a textarea that springs to fit with a character-limit counter, and an AI chat input with Enter to send and a loading state.
- Drop-in shadcn API
- Server Component friendly
- Auto-resize
- Character counter
- Motion blocks
- Ship the animated form components today?
"use client";
import * as React from "react";
import { AtSign, Paperclip } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ChatInput } from "@/components/dusk/textarea/chat-input";
export default function ChatInputDemo() {
const [messages, setMessages] = React.useState<string[]>(["Ship the animated form components today?"]);
return (
<div className="grid w-full max-w-md gap-3">
<ul className="grid gap-2" aria-label="Messages" aria-live="polite">
{messages.map((message, i) => (
<li
key={i}
className="max-w-[85%] justify-self-end rounded-xl rounded-br-sm bg-muted px-3 py-2 text-sm whitespace-pre-wrap text-foreground"
>
{message}
</li>
))}
</ul>
<ChatInput
aria-label="Message"
placeholder="Ask anything…"
onSubmit={(message) =>
// Pretend to send it: the button shows a spinner until this resolves.
new Promise<void>((resolve) =>
setTimeout(() => {
setMessages((list) => [...list.slice(-2), message]);
resolve();
}, 900)
)
}
actions={
<>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Attach a file" className="rounded-full">
<Paperclip />
</Button>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Mention someone" className="rounded-full">
<AtSign />
</Button>
</>
}
/>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/textarea.json1. Copy the source into
components/ui/textarea.tsx.textarea.tsx import * as React from "react"; import { cn } from "@/lib/utils"; /** * DuskUI Textarea — a drop-in upgrade of the shadcn/ui Textarea. * * Same API as shadcn. It grows with its content (`field-sizing: content`) * between a 4rem minimum and whatever `max-h-*` you give it, then scrolls. * Adds the Input's hover state, soft focus ring, clear invalid state and a * tidy scrollbar. Set `className="field-sizing-fixed"` and `rows` for a * fixed-height box. CSS only, so it works in Server Components. */ function Textarea({ className, ...props }: React.ComponentProps<"textarea">) { return ( <textarea data-slot="textarea" className={cn( "flex field-sizing-content min-h-16 w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs outline-none md:text-sm dark:bg-input/30", "transition-[color,background-color,border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none", "placeholder:text-muted-foreground placeholder:transition-opacity focus:placeholder:opacity-60", "selection:bg-primary selection:text-primary-foreground", "dark:hover:bg-input/40", "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50", "aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40", "disabled:cursor-not-allowed disabled:opacity-50", "read-only:bg-muted/40 read-only:focus-visible:ring-0", "[scrollbar-color:var(--color-border)_transparent] [scrollbar-width:thin]", className )} {...props} /> ); } export { Textarea };
Replaces components/ui/textarea.tsx with the same API. The base Textarea is CSS-only — no "use client" needed. It grows with field-sizing: content; browsers without it keep a fixed height.
Usage
import { Textarea } from "@/components/ui/textarea"
export function Feedback() {
return <Textarea aria-label="Feedback" placeholder="What can we improve?" className="max-h-48" />
}Examples
Default
Start typing: the field grows with its content. Cap it with a max-h-* class and it scrolls from there.
import { Textarea } from "@/components/ui/textarea";
export default function TextareaBasicDemo() {
return (
<Textarea
aria-label="Message"
placeholder="Type your message here. The field grows as you write."
className="max-h-48 w-full max-w-md"
/>
);
}With label & hint
Pair the field with a <label> and link hints with aria-describedby.
Shown on your public profile. Markdown is supported.
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
export default function TextareaWithLabelDemo() {
return (
<div className="grid w-full max-w-md gap-2">
<label htmlFor="bio" className="text-sm font-medium">
Bio
</label>
<Textarea
id="bio"
placeholder="Tell us a little about yourself"
aria-describedby="bio-hint"
className="max-h-40"
/>
<p id="bio-hint" className="text-xs text-muted-foreground">
Shown on your public profile. Markdown is supported.
</p>
<Button size="sm" className="justify-self-end">
Save bio
</Button>
</div>
);
}Invalid, disabled & fixed
aria-invalid turns the border red, disabled dims it, and field-sizing-fixed with rows gives a classic fixed-height box.
Feedback must be at least 10 characters.
import { Textarea } from "@/components/ui/textarea";
export default function TextareaStatesDemo() {
return (
<div className="grid w-full max-w-md gap-4">
<div className="grid gap-1.5">
<Textarea
aria-label="Feedback"
aria-invalid
aria-describedby="feedback-error"
defaultValue="meh"
/>
<p id="feedback-error" className="text-xs text-destructive">
Feedback must be at least 10 characters.
</p>
</div>
<Textarea aria-label="Disabled" placeholder="Comments are turned off" disabled />
<Textarea
aria-label="Fixed height"
rows={3}
className="field-sizing-fixed resize-y"
placeholder="field-sizing-fixed + rows for a fixed, resizable box"
/>
</div>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Auto-resize Textarea
Springs to fit its content instead of jumping a line at a time, between minRows and maxRows. With maxLength, a ring fills as you type and turns amber near the limit, then red, with the characters left sliding in. It measures an invisible twin with a ResizeObserver, so it works in every browser.
import { AutoResizeTextarea } from "@/components/dusk/textarea/auto-resize-textarea";
export default function AutoResizeTextareaDemo() {
return (
<div className="grid w-full max-w-md gap-2">
<label htmlFor="release-notes" className="text-sm font-medium">
Release notes
</label>
<AutoResizeTextarea
id="release-notes"
placeholder="What changed in this release?"
maxLength={180}
minRows={2}
maxRows={7}
defaultValue={"Animated select, radio cards and a chat input.\nThe list springs open from the trigger."}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/auto-resize-textarea.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/textarea/auto-resize-textarea.tsx.auto-resize-textarea.tsx "use client"; import * as React from "react"; import { AnimatePresence, motion, useReducedMotion, type Transition } from "motion/react"; import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; const heightSpring: Transition = { type: "spring", bounce: 0, duration: 0.25 }; // Shared by the textarea and its invisible twin, so both wrap text identically. const metrics = "px-3 py-2 text-base leading-6 md:text-sm md:leading-6 border"; export interface AutoResizeTextareaProps extends Omit<React.ComponentProps<"textarea">, "value" | "defaultValue" | "rows"> { value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Height when empty, in lines. */ minRows?: number; /** Grows up to this many lines, then scrolls. */ maxRows?: number; /** Character limit. Shows a counter ring that turns amber, then red, near the limit. */ maxLength?: number; /** Fraction of `maxLength` at which the counter turns amber. */ warnAt?: number; /** `false` lets people type past the limit and marks the field invalid instead of blocking input. */ enforceLimit?: boolean; /** Classes for the wrapper. `className` styles the textarea. */ containerClassName?: string; } /** * A textarea that springs to fit its content instead of jumping a line at a * time, between `minRows` and `maxRows`. An invisible twin with the same text * is measured with a ResizeObserver, so it works in every browser and never * reads layout on keystrokes. With `maxLength` a counter ring fills as you * type and turns amber, then red near the limit; screen readers hear only the * threshold changes, not every keystroke. Under reduced motion the height * changes instantly. */ export function AutoResizeTextarea({ value: valueProp, defaultValue = "", onValueChange, onChange, minRows = 2, maxRows = 8, maxLength, warnAt = 0.8, enforceLimit = true, className, containerClassName, id, "aria-describedby": ariaDescribedBy, "aria-invalid": ariaInvalid, ...props }: AutoResizeTextareaProps) { const autoId = React.useId(); const fieldId = id ?? autoId; const counterId = `${fieldId}-counter`; const reduceMotion = useReducedMotion(); const twinRef = React.useRef<HTMLDivElement>(null); const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const [height, setHeight] = React.useState<number | null>(null); const value = valueProp ?? uncontrolled; React.useLayoutEffect(() => { const twin = twinRef.current; if (!twin) return; const observer = new ResizeObserver(([entry]) => setHeight(Math.round(entry.borderBoxSize?.[0]?.blockSize ?? twin.offsetHeight)) ); observer.observe(twin); return () => observer.disconnect(); }, []); const count = value.length; const ratio = maxLength ? count / maxLength : 0; const level = !maxLength ? "ok" : count > maxLength ? "over" : count === maxLength ? "full" : ratio >= warnAt ? "warn" : "ok"; const remaining = maxLength ? maxLength - count : 0; const invalid = ariaInvalid ?? (level === "over" || undefined); // Lines are 1.5rem; padding + border add 1.125rem (2.375rem with room for the counter). const chrome = maxLength ? 2.375 : 1.125; const minHeight = `${minRows * 1.5 + chrome}rem`; const maxHeight = `${maxRows * 1.5 + chrome}rem`; return ( <div data-slot="auto-resize-textarea" className={cn("relative w-full", containerClassName)}> {/* The twin: same text, same metrics, invisible. Its height is the target height. */} <div ref={twinRef} aria-hidden className={cn( "pointer-events-none invisible absolute inset-x-0 top-0 overflow-hidden border-transparent break-words whitespace-pre-wrap", metrics, maxLength && "pb-7" )} style={{ minHeight, maxHeight }} > {/* A trailing newline needs a character after it to take up a line. */} {value}{" "} </div> <motion.div initial={false} animate={height === null ? undefined : { height }} transition={reduceMotion ? { duration: 0 } : heightSpring} className="relative" style={{ minHeight }} > <Textarea id={fieldId} value={value} maxLength={enforceLimit ? maxLength : undefined} aria-invalid={invalid} aria-describedby={cn(ariaDescribedBy, maxLength && counterId) || undefined} onChange={(event) => { if (valueProp === undefined) setUncontrolled(event.target.value); onValueChange?.(event.target.value); onChange?.(event); }} className={cn("field-sizing-fixed h-full min-h-0 resize-none", metrics, maxLength && "pb-7", className)} {...props} /> </motion.div> {maxLength ? ( <CharacterCounter id={counterId} count={count} max={maxLength} level={level} remaining={remaining} reduceMotion={reduceMotion ?? false} /> ) : null} </div> ); } type Level = "ok" | "warn" | "full" | "over"; const levelColor: Record<Level, string> = { ok: "text-muted-foreground", warn: "text-amber-400", full: "text-destructive", over: "text-destructive", }; function CharacterCounter({ id, count, max, level, remaining, reduceMotion, }: { id: string; count: number; max: number; level: Level; remaining: number; reduceMotion: boolean; }) { const progress = Math.min(count / max, 1); const radius = 7; const circumference = 2 * Math.PI * radius; const showNumber = level !== "ok"; const announcement = level === "over" ? `${-remaining} characters over the limit` : level === "full" ? "Character limit reached" : level === "warn" ? `${remaining} characters left` : ""; // Announce only when the level changes, not on every keystroke. const [spoken, setSpoken] = React.useState(""); const [lastLevel, setLastLevel] = React.useState<Level>(level); if (lastLevel !== level) { setLastLevel(level); setSpoken(announcement); } return ( <div className={cn( "pointer-events-none absolute right-2.5 bottom-2 flex items-center gap-1.5 text-xs tabular-nums transition-colors duration-200", levelColor[level] )} > <AnimatePresence initial={false} mode="popLayout"> {showNumber && ( <motion.span key="number" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, x: 4 }} animate={{ opacity: 1, x: 0 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, x: 4 }} transition={{ type: "spring", duration: 0.3, bounce: 0 }} > {remaining} </motion.span> )} </AnimatePresence> <motion.svg viewBox="0 0 18 18" className="size-4.5 -rotate-90" aria-hidden animate={level === "full" || level === "over" ? (reduceMotion ? {} : { scale: [1, 1.1, 1] }) : { scale: 1 }} transition={{ duration: 0.3 }} > <circle cx="9" cy="9" r={radius} fill="none" stroke="currentColor" strokeOpacity={0.2} strokeWidth={2} /> <motion.circle cx="9" cy="9" r={radius} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeDasharray={circumference} initial={false} animate={{ strokeDashoffset: circumference * (1 - progress) }} transition={reduceMotion ? { duration: 0 } : { type: "spring", duration: 0.3, bounce: 0 }} className={cn(level === "ok" && "text-foreground/70")} /> </motion.svg> <span id={id} className="sr-only"> {count} of {max} characters used </span> <span className="sr-only" aria-live="polite"> {spoken} </span> </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| value / onValueChange | string / (value: string) => void | — | Controlled text. |
| defaultValue | string | "" | Uncontrolled initial text. |
| minRows | number | 2 | Height when empty, in lines. |
| maxRows | number | 8 | Grows up to this many lines, then scrolls. |
| maxLength | number | — | Character limit; shows the counter ring. |
| warnAt | number | 0.8 | Fraction of maxLength where the counter turns amber. |
| enforceLimit | boolean | true | false lets people type past the limit and marks the field invalid instead. |
| containerClassName | string | — | Classes for the wrapper. `className` styles the textarea. |
Chat Input
A composer for chat and AI prompts. Enter sends, Shift+Enter adds a line, and IME composition is never interrupted. The send button wakes up with a spring once there is text, and swaps to a spinner without changing size while onSubmit's promise is pending (the DuskUI Button loading prop). If the promise rejects, the text comes back. Put attach or model buttons in actions.
- Ship the animated form components today?
"use client";
import * as React from "react";
import { AtSign, Paperclip } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ChatInput } from "@/components/dusk/textarea/chat-input";
export default function ChatInputDemo() {
const [messages, setMessages] = React.useState<string[]>(["Ship the animated form components today?"]);
return (
<div className="grid w-full max-w-md gap-3">
<ul className="grid gap-2" aria-label="Messages" aria-live="polite">
{messages.map((message, i) => (
<li
key={i}
className="max-w-[85%] justify-self-end rounded-xl rounded-br-sm bg-muted px-3 py-2 text-sm whitespace-pre-wrap text-foreground"
>
{message}
</li>
))}
</ul>
<ChatInput
aria-label="Message"
placeholder="Ask anything…"
onSubmit={(message) =>
// Pretend to send it: the button shows a spinner until this resolves.
new Promise<void>((resolve) =>
setTimeout(() => {
setMessages((list) => [...list.slice(-2), message]);
resolve();
}, 900)
)
}
actions={
<>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Attach a file" className="rounded-full">
<Paperclip />
</Button>
<Button type="button" variant="ghost" size="icon-sm" aria-label="Mention someone" className="rounded-full">
<AtSign />
</Button>
</>
}
/>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/chat-input.json1. Install the dependencies.
npm install motion lucide-react2. Copy the source into
components/dusk/textarea/chat-input.tsx.chat-input.tsx "use client"; import * as React from "react"; import { ArrowUp } from "lucide-react"; import { motion, useReducedMotion } from "motion/react"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { cn } from "@/lib/utils"; export interface ChatInputProps extends Omit<React.ComponentProps<"textarea">, "value" | "defaultValue" | "onSubmit"> { value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** * Called with the trimmed message on Enter or the send button. Return a * promise to show the loading state until it settles. Uncontrolled inputs * clear right away and get the text back if the promise rejects. */ onSubmit?: (message: string) => void | Promise<unknown>; /** Show the send button's spinner and block sending (e.g. while a reply streams). */ loading?: boolean; /** Extra controls on the left of the toolbar (attach, model picker…). */ actions?: React.ReactNode; /** Accessible name for the send button. */ sendLabel?: string; /** Classes for the outer container. `className` styles the textarea. */ containerClassName?: string; } /** * A chat composer: a textarea that grows with the message (up to `max-h`, * then scrolls) and a send button. Enter sends, Shift+Enter adds a new line, * and IME composition (Japanese, Chinese…) is never interrupted. The send * button wakes up with a little spring once there is something to send and * swaps to a spinner (the DuskUI Button `loading` prop) without changing size * while the message is sending. Click anywhere on the container to focus. */ export function ChatInput({ value: valueProp, defaultValue = "", onValueChange, onSubmit, loading: loadingProp = false, actions, sendLabel = "Send message", placeholder = "Send a message…", disabled, className, containerClassName, onKeyDown, "aria-describedby": ariaDescribedBy, ...props }: ChatInputProps) { const hintId = React.useId(); const reduceMotion = useReducedMotion(); const textareaRef = React.useRef<HTMLTextAreaElement>(null); const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const [pending, setPending] = React.useState(false); const value = valueProp ?? uncontrolled; const loading = loadingProp || pending; const canSend = value.trim().length > 0 && !loading && !disabled; const update = (next: string) => { if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; const submit = async () => { if (!canSend) return; const message = value.trim(); if (valueProp === undefined) setUncontrolled(""); const result = onSubmit?.(message); if (!(result instanceof Promise)) return; setPending(true); try { await result; } catch { // Give the text back so nothing is lost. if (valueProp === undefined) setUncontrolled(message); } finally { setPending(false); } }; return ( <div data-slot="chat-input" data-disabled={disabled || undefined} onPointerDown={(event) => { // Clicking the padding or toolbar focuses the field, but not buttons inside it. if (event.target === event.currentTarget) { event.preventDefault(); textareaRef.current?.focus(); } }} className={cn( "group/chat relative w-full cursor-text rounded-xl border border-input bg-input/30 p-2 shadow-xs", "transition-[border-color,box-shadow,background-color] duration-200 ease-out motion-reduce:transition-none", "focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50", "data-disabled:cursor-not-allowed data-disabled:opacity-50", containerClassName )} > <Textarea ref={textareaRef} rows={1} value={value} disabled={disabled} placeholder={placeholder} aria-busy={loading || undefined} aria-describedby={cn(ariaDescribedBy, hintId)} enterKeyHint="send" onChange={(event) => update(event.target.value)} onKeyDown={(event) => { onKeyDown?.(event); if (event.defaultPrevented) return; if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void submit(); } }} className={cn( "max-h-48 min-h-10 resize-none border-0 bg-transparent px-2 py-1.5 shadow-none", "hover:bg-transparent focus-visible:ring-0 dark:bg-transparent dark:hover:bg-transparent", className )} {...props} /> <div className="flex items-center gap-1.5 pt-1" onPointerDown={(event) => { if (event.target === event.currentTarget) { event.preventDefault(); textareaRef.current?.focus(); } }} > {actions} <span id={hintId} className="sr-only"> Press Enter to send, Shift+Enter for a new line. </span> <span aria-hidden className="ml-auto hidden text-[11px] text-muted-foreground/70 opacity-0 transition-opacity duration-200 group-focus-within/chat:opacity-100 sm:inline"> <kbd className="font-sans">Shift</kbd> + <kbd className="font-sans">Enter</kbd> for a new line </span> <motion.div className="ml-auto sm:ml-1.5" initial={false} animate={canSend || loading ? { scale: 1, opacity: 1 } : { scale: reduceMotion ? 1 : 0.96, opacity: 0.6 }} transition={{ duration: 0.15, ease: "easeOut" }} > <Button type="button" size="icon-sm" loading={loading} disabled={!canSend && !loading} aria-label={sendLabel} onClick={() => { void submit(); textareaRef.current?.focus(); }} className="rounded-full disabled:opacity-100 disabled:bg-muted disabled:text-muted-foreground disabled:shadow-none" > <ArrowUp className="size-4" strokeWidth={2.5} /> </Button> </motion.div> </div> </div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| onSubmit | (message: string) => void | Promise | — | Called with the trimmed text. Return a promise to show loading until it settles. |
| value / onValueChange | string / (value: string) => void | — | Controlled text. Uncontrolled inputs clear themselves on send. |
| defaultValue | string | "" | Uncontrolled initial text. |
| loading | boolean | false | Show the spinner and block sending, e.g. while a reply streams. |
| actions | ReactNode | — | Extra controls on the left of the toolbar. |
| sendLabel | string | "Send message" | Accessible name of the send button. |
| containerClassName | string | — | Classes for the outer box. `className` styles the textarea (e.g. max-h-*). |
API Reference
Textarea takes every native <textarea> prop, exactly like shadcn/ui.
| Prop | Type | Default | Description |
|---|---|---|---|
| className | string | — | Add max-h-* to cap the auto-grow; field-sizing-fixed to turn it off. |
| rows | number | — | Initial height when field-sizing-fixed is set. |
| aria-invalid | boolean | — | Red border and ring for validation errors. |
| disabled / readOnly | boolean | — | Dimmed, or a muted surface without a focus ring. |
Accessibility
- It is a native <textarea>: name it with a <label htmlFor> or aria-label, and link hints and errors with aria-describedby.
- Auto-resize Textarea links the counter with aria-describedby and announces only threshold changes ("20 characters left", "Character limit reached") through a polite live region, not every keystroke.
- Chat Input explains Enter / Shift+Enter in an sr-only hint linked to the field, sets enterKeyHint="send" for mobile keyboards, and keeps the send button focusable while loading (aria-busy + aria-disabled).
- Under prefers-reduced-motion the height changes instantly and the counter and send button only fade.