# useAutosizeTextarea

Grows a `<textarea>` to fit its text, up to `maxRows` lines, then scrolls. Returns a callback ref for the textarea. Set the minimum with the textarea's own `rows` attribute.

Resizes on typing and paste, when a controlled `value` changes from code (e.g. cleared after sending), and when the textarea's width changes and the text rewraps. Handles padding, borders, and `box-sizing`. Works the same in every browser; CSS `field-sizing: content` does this natively but is not supported everywhere yet.

## Import

```ts
import { useAutosizeTextarea } from '@vincent.ri/react-tils'
// or only this hook
import { useAutosizeTextarea } from '@vincent.ri/react-tils/useAutosizeTextarea'
```

## Usage

```ts
const [message, setMessage] = useState('')
const ref = useAutosizeTextarea({ maxRows: 8 })
return (
  <textarea ref={ref} rows={1} value={message} onChange={(e) => setMessage(e.target.value)} />
)
```

## When to use it

Chat inputs, comment boxes, or any text box that should grow with its content.

## When not to

The textarea has a fixed height, or every browser you support has `field-sizing: content`.

## API

```ts
function useAutosizeTextarea(options?: AutosizeTextareaOptions): (element: HTMLTextAreaElement | null) => void
```

| Parameter | Description |
| --- | --- |
| `options` | `maxRows`. Optional. |

**Returns** A callback ref. Pass it to the textarea's `ref` prop.

### Types

```ts
export type AutosizeTextareaOptions = {
  /** Stop growing after this many lines and scroll instead. Default: no limit. */
  maxRows?: number | undefined;
};
```

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useTextareaAutosize`, `useAutoResize`, `react-textarea-autosize`.

---

474 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useAutosizeTextarea.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useAutosizeTextarea/
Previous: [useFocusWithin](https://vincentri.github.io/react-tils/hooks/useFocusWithin.md)
Next: [useCaretPosition](https://vincentri.github.io/react-tils/hooks/useCaretPosition.md)
