Textarea
55 lines · 1 file · MIT
Several lines in the field's look, with a character count when it has a limit.
import { forwardRef, useState, type TextareaHTMLAttributes } from "react";
import { cn } from "./cn";
import { inputClass, NO_AUTOFILL, useFieldAria } from "./field";
/**
* Several lines of input in the field's look: the same ring, the same focus
* and the same invalid mark, grown to the rows it is given. Give it a
* `maxLength` and a count appears in the corner, turning to the danger colour
* at the limit. Inside a Field it takes the field's error on its own.
*/
export const Textarea = forwardRef<
HTMLTextAreaElement,
TextareaHTMLAttributes<HTMLTextAreaElement>
>(({ className, maxLength, onChange, defaultValue, value, ...props }, ref) => {
const aria = useFieldAria();
const [own, setOwn] = useState(String(defaultValue ?? ""));
const length = value === undefined ? own.length : String(value).length;
return (
<span className="relative block min-w-0">
<textarea
ref={ref}
rows={4}
maxLength={maxLength}
value={value}
defaultValue={defaultValue}
onChange={(e) => {
setOwn(e.target.value);
onChange?.(e);
}}
className={cn(
inputClass,
"block h-auto resize-y py-2 leading-relaxed",
maxLength && "pb-7",
className,
)}
{...(!props.autoComplete || props.autoComplete === "off" ? NO_AUTOFILL : undefined)}
{...aria}
{...props}
/>
{maxLength !== undefined && (
<span
aria-hidden
className={cn(
"pointer-events-none absolute right-3 bottom-2 text-xs tabular-nums",
length >= maxLength ? "text-danger" : "text-muted",
)}
>
{length}/{maxLength}
</span>
)}
</span>
);
});
Textarea.displayName = "Textarea";
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/textarea- Category
- Forms
- Files
- textarea.tsx