Docs
useAutosizeTextarea
Automatically resize a textarea to fit its content with useAutosizeTextarea.
Loading...
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-autosize-textarea
Usage
"use client"
import * as React from "react"
import { useAutosizeTextArea } from "@/hooks/use-autosize-textarea"
export function Component() {
const textAreaRef = React.useRef<HTMLTextAreaElement>(null)
const [value, setValue] = React.useState("")
// Resize textarea when value changes
useAutosizeTextArea({
ref: textAreaRef,
maxHeight: 200, // Max height of 200px
borderWidth: 1, // Account for 1px border
dependencies: [value], // Re-run effect when value changes
})
return (
<textarea
ref={textAreaRef}
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Type here..."
style={{ borderWidth: "1px" }}
/>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
ref | RefObject<HTMLTextAreaElement> | A React ref object pointing to the <textarea> element to resize. | Required | No |
maxHeight | number | The maximum height (in pixels) the textarea can grow to. | Number.MAX_SAFE_INTEGER | Yes |
borderWidth | number | The width (in pixels) of the textarea's border, used for height adjustments. | 0 | Yes |
dependencies | DependencyList | An array of dependencies to trigger resizing when they change. | [] (empty array) | Yes |