React textarea component that automatically resizes to fit content with configurable row limits
npx @tessl/cli install tessl/npm-react-textarea-autosize@8.5.00
# React Textarea Autosize
1
2
React Textarea Autosize is a drop-in replacement for the standard HTML textarea element that automatically resizes based on content. The component maintains all standard textarea functionality while intelligently adjusting height as users type, with configurable minimum and maximum row limits.
3
4
## Package Information
5
6
- **Package Name**: react-textarea-autosize
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-textarea-autosize`
10
11
## Core Imports
12
13
```typescript
14
import TextareaAutosize from "react-textarea-autosize";
15
import type { TextareaAutosizeProps, TextareaHeightChangeMeta } from "react-textarea-autosize";
16
```
17
18
Note: The component is the default export. TypeScript types are available for import using `import type` syntax.
19
20
For CommonJS:
21
22
```javascript
23
const TextareaAutosize = require("react-textarea-autosize").default;
24
```
25
26
## Basic Usage
27
28
```typescript
29
import React from "react";
30
import TextareaAutosize from "react-textarea-autosize";
31
32
function MyForm() {
33
return (
34
<div>
35
<TextareaAutosize
36
placeholder="Enter your message..."
37
minRows={3}
38
maxRows={10}
39
style={{ width: "100%" }}
40
/>
41
</div>
42
);
43
}
44
```
45
46
## Architecture
47
48
React Textarea Autosize is built around several key components:
49
50
- **Main Component**: `TextareaAutosize` - A React component using `forwardRef` for direct textarea access
51
- **Auto-sizing Engine**: Calculates height using hidden textarea measurements and CSS sizing data
52
- **Event Integration**: Listens to window resize, font loading, and form reset events
53
- **Performance Optimization**: Optional measurement caching to avoid repeated calculations
54
- **Browser Compatibility**: Handles different environments (browser vs SSR) with graceful fallbacks
55
56
## Capabilities
57
58
### TextareaAutosize Component
59
60
A React component that renders an auto-resizing textarea element with all standard textarea functionality plus intelligent height adjustment.
61
62
```typescript { .api }
63
declare const TextareaAutosize: React.ForwardRefExoticComponent<
64
TextareaAutosizeProps & React.RefAttributes<HTMLTextAreaElement>
65
>;
66
67
interface TextareaAutosizeProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'style'> {
68
/** Maximum number of rows the textarea can grow to */
69
maxRows?: number;
70
/** Minimum number of rows to show */
71
minRows?: number;
72
/** Callback fired when textarea height changes */
73
onHeightChange?: (height: number, meta: TextareaHeightChangeMeta) => void;
74
/** Whether to cache measurements for performance optimization */
75
cacheMeasurements?: boolean;
76
/** Style object that excludes maxHeight and minHeight properties */
77
style?: Style;
78
}
79
80
interface TextareaHeightChangeMeta {
81
/** Height of a single row in pixels */
82
rowHeight: number;
83
}
84
85
type Style = Omit<
86
NonNullable<React.TextareaHTMLAttributes<HTMLTextAreaElement>['style']>,
87
'maxHeight' | 'minHeight'
88
> & {
89
/** Height can be set as a number (in pixels) */
90
height?: number;
91
};
92
```
93
94
**Usage Examples:**
95
96
```typescript
97
import React, { useState } from "react";
98
import TextareaAutosize from "react-textarea-autosize";
99
100
// Basic auto-resizing textarea
101
function BasicExample() {
102
return (
103
<TextareaAutosize
104
placeholder="Type something..."
105
style={{ width: "100%", padding: 8 }}
106
/>
107
);
108
}
109
110
// Controlled component with value
111
function ControlledExample() {
112
const [value, setValue] = useState("");
113
114
return (
115
<TextareaAutosize
116
value={value}
117
onChange={(e) => setValue(e.target.value)}
118
minRows={2}
119
maxRows={8}
120
placeholder="Enter your story..."
121
/>
122
);
123
}
124
125
// With height change callback
126
function CallbackExample() {
127
const handleHeightChange = (height: number, meta: TextareaHeightChangeMeta) => {
128
console.log(`New height: ${height}px, Row height: ${meta.rowHeight}px`);
129
};
130
131
return (
132
<TextareaAutosize
133
onHeightChange={handleHeightChange}
134
minRows={1}
135
maxRows={5}
136
placeholder="Type to see height changes..."
137
/>
138
);
139
}
140
141
// With ref for direct access
142
function RefExample() {
143
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
144
145
const focusTextarea = () => {
146
textareaRef.current?.focus();
147
};
148
149
return (
150
<div>
151
<TextareaAutosize
152
ref={textareaRef}
153
placeholder="Click button to focus"
154
/>
155
<button onClick={focusTextarea}>Focus Textarea</button>
156
</div>
157
);
158
}
159
160
// Performance optimized with caching
161
function CachedExample() {
162
return (
163
<TextareaAutosize
164
cacheMeasurements={true}
165
minRows={3}
166
maxRows={15}
167
placeholder="Large content with cached measurements..."
168
/>
169
);
170
}
171
```
172
173
### Row Configuration
174
175
Control the minimum and maximum size of the textarea using row-based constraints.
176
177
```typescript { .api }
178
interface RowProps {
179
/** Minimum number of rows to display (default: 1) */
180
minRows?: number;
181
/** Maximum number of rows before scrolling (default: Infinity) */
182
maxRows?: number;
183
}
184
```
185
186
- `minRows`: Sets the minimum height in rows - textarea won't shrink below this size
187
- `maxRows`: Sets the maximum height in rows - textarea will scroll if content exceeds this size
188
- Both props accept positive numbers, with `maxRows` defaulting to `Infinity` (no limit)
189
190
### Height Change Callback
191
192
Receive notifications when the textarea height changes, useful for layout adjustments or analytics.
193
194
```typescript { .api }
195
type HeightChangeHandler = (height: number, meta: TextareaHeightChangeMeta) => void;
196
197
interface TextareaHeightChangeMeta {
198
/** The calculated height of a single row in pixels */
199
rowHeight: number;
200
}
201
```
202
203
The callback provides:
204
- `height`: New total height of the textarea in pixels
205
- `meta.rowHeight`: Height of a single text row, useful for calculating row counts
206
207
### Performance Optimization
208
209
Optional caching mechanism to improve performance when dealing with frequently changing content.
210
211
```typescript { .api }
212
interface CachingOptions {
213
/** Cache CSS measurements to avoid repeated DOM queries */
214
cacheMeasurements?: boolean;
215
}
216
```
217
218
When `cacheMeasurements` is `true`:
219
- CSS sizing data is cached after first calculation
220
- Subsequent resizes use cached measurements instead of re-querying DOM
221
- Improves performance for rapid content changes
222
- Cache is automatically cleared when component unmounts
223
224
### Style Constraints
225
226
The component accepts all standard textarea styles except `maxHeight` and `minHeight`, which conflict with the row-based sizing system.
227
228
```typescript { .api }
229
type Style = Omit<
230
NonNullable<React.TextareaHTMLAttributes<HTMLTextAreaElement>['style']>,
231
'maxHeight' | 'minHeight'
232
> & {
233
height?: number;
234
};
235
```
236
237
**Important Style Notes:**
238
- `maxHeight` and `minHeight` CSS properties are not allowed - use `maxRows` and `minRows` props instead
239
- `height` can be set as a number (interpreted as pixels) for initial sizing
240
- All other CSS properties work normally (width, padding, border, etc.)
241
- Component throws errors in development mode if restricted properties are used
242
243
## Error Handling
244
245
The component performs validation in development mode and throws descriptive errors for common mistakes:
246
247
- **`maxHeight` style error**: Thrown when `style.maxHeight` is provided - use `maxRows` prop instead
248
- **`minHeight` style error**: Thrown when `style.minHeight` is provided - use `minRows` prop instead
249
250
These errors only occur in development builds to help catch configuration issues early.
251
252
## Browser Compatibility
253
254
- **Modern Browsers**: Full functionality with all features
255
- **Internet Explorer 9+**: Supported with polyfills
256
- **Server-Side Rendering**: Compatible - renders standard textarea on server, upgrades to auto-resize on client
257
- **Edge Cases**: Graceful fallback to standard textarea behavior when JavaScript is disabled
258
259
## Environment Detection
260
261
The component automatically detects the runtime environment:
262
- **Browser**: Full auto-resize functionality with event listeners
263
- **Server/SSR**: Renders static textarea without client-side features
264
- **Edge Runtime**: Optimized build for edge computing environments