An auto-resizing text area dynamically adjusts its height based on its content
const AutoResizeTextarea = (props) => { const { onChange = () => {}, style = {}, ...rest } = props; const textAreaRef = useRef(); const [textAreaHeight, setTextAreaHeight] = useState("auto"); const handleChange = (e) => { onChange(e); handleAutoResize(e); }; useEffect(() => { setTextAreaHeight( textAreaRef.current?.scrollHeight ? `${textAreaRef.current?.scrollHeight}px` : "auto" ); }, []); const handleAutoResize = (event) => { if (textAreaRef?.current) { textAreaRef.current.style.height = "auto"; textAreaRef.current.style.height = `${event.target.scrollHeight}px`; } }; return ( <textarea ref={textAreaRef} style={{ height: textAreaHeight, resize: "none", ...style, }} rows={1} onChange={(e) => handleChange(e)} {...rest} /> ); }; export default AutoResizeTextarea;