How to auto-resize a textarea
A textarea that grows as people type feels much better than one that scrolls inside a tiny box. There is now a one-line CSS answer, and a small JavaScript fallback for older browsers.
The modern CSS way: field-sizing
The field-sizing: content property makes form controls size themselves to their content. Add a minimum and maximum so it doesn't collapse or grow forever:
textarea {
field-sizing: content;
min-height: 3lh; /* about three lines */
max-height: 12lh; /* then scroll */
}Browser support is still growing, so use the React approach below as a fallback or when you need precise control.
The React way: measure scrollHeight
Reset the height to auto, read scrollHeight and set the height to match. Do it whenever the value changes:
import { useLayoutEffect, useRef } from 'react';
export function AutoTextarea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
const ref = useRef<HTMLTextAreaElement>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 320) + 'px';
}, [props.value]);
return <textarea ref={ref} rows={2} {...props} className="resize-none overflow-y-auto" />;
}How to disable textarea resizing
Browsers show a drag handle in the corner of a textarea. Remove it, or allow vertical resizing only:
textarea { resize: none; } /* no handle */
textarea { resize: vertical; } /* height only */In Tailwind, use resize-none, resize-y or resize-x.
Ready-made components
NiceUI's Auto-Resize Textarea adds a character counter, min and max rows and a custom drag handle, and the Resizable Panels component gives you draggable split panes with keyboard support:
FAQ
How do I make a textarea expand automatically?
Use field-sizing: content in CSS, or set the height to its scrollHeight on every input in JavaScript.
How do I stop a textarea from being resized?
Add resize: none in CSS, or the resize-none class in Tailwind.
Why does my auto-resizing textarea jump?
Set the height to auto before reading scrollHeight, and run the update in useLayoutEffect so it happens before paint.