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

NameTypeDescriptionDefault ValueOptional
refRefObject<HTMLTextAreaElement>A React ref object pointing to the <textarea> element to resize.RequiredNo
maxHeightnumberThe maximum height (in pixels) the textarea can grow to.Number.MAX_SAFE_INTEGERYes
borderWidthnumberThe width (in pixels) of the textarea's border, used for height adjustments.0Yes
dependenciesDependencyListAn array of dependencies to trigger resizing when they change.[] (empty array)Yes