or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-react-textarea-autosize

React textarea component that automatically resizes to fit content with configurable row limits

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/react-textarea-autosize@8.5.x

To install, run

npx @tessl/cli install tessl/npm-react-textarea-autosize@8.5.0

index.mddocs/

React Textarea Autosize

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.

Package Information

  • Package Name: react-textarea-autosize
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install react-textarea-autosize

Core Imports

import TextareaAutosize from "react-textarea-autosize";
import type { TextareaAutosizeProps, TextareaHeightChangeMeta } from "react-textarea-autosize";

Note: The component is the default export. TypeScript types are available for import using import type syntax.

For CommonJS:

const TextareaAutosize = require("react-textarea-autosize").default;

Basic Usage

import React from "react";
import TextareaAutosize from "react-textarea-autosize";

function MyForm() {
  return (
    <div>
      <TextareaAutosize
        placeholder="Enter your message..."
        minRows={3}
        maxRows={10}
        style={{ width: "100%" }}
      />
    </div>
  );
}

Architecture

React Textarea Autosize is built around several key components:

  • Main Component: TextareaAutosize - A React component using forwardRef for direct textarea access
  • Auto-sizing Engine: Calculates height using hidden textarea measurements and CSS sizing data
  • Event Integration: Listens to window resize, font loading, and form reset events
  • Performance Optimization: Optional measurement caching to avoid repeated calculations
  • Browser Compatibility: Handles different environments (browser vs SSR) with graceful fallbacks

Capabilities

TextareaAutosize Component

A React component that renders an auto-resizing textarea element with all standard textarea functionality plus intelligent height adjustment.

declare const TextareaAutosize: React.ForwardRefExoticComponent<
  TextareaAutosizeProps & React.RefAttributes<HTMLTextAreaElement>
>;

interface TextareaAutosizeProps extends Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'style'> {
  /** Maximum number of rows the textarea can grow to */
  maxRows?: number;
  /** Minimum number of rows to show */
  minRows?: number;
  /** Callback fired when textarea height changes */
  onHeightChange?: (height: number, meta: TextareaHeightChangeMeta) => void;
  /** Whether to cache measurements for performance optimization */
  cacheMeasurements?: boolean;  
  /** Style object that excludes maxHeight and minHeight properties */
  style?: Style;
}

interface TextareaHeightChangeMeta {
  /** Height of a single row in pixels */
  rowHeight: number;
}

type Style = Omit<
  NonNullable<React.TextareaHTMLAttributes<HTMLTextAreaElement>['style']>,
  'maxHeight' | 'minHeight'
> & {
  /** Height can be set as a number (in pixels) */
  height?: number;
};

Usage Examples:

import React, { useState } from "react";
import TextareaAutosize from "react-textarea-autosize";

// Basic auto-resizing textarea
function BasicExample() {
  return (
    <TextareaAutosize
      placeholder="Type something..."
      style={{ width: "100%", padding: 8 }}
    />
  );
}

// Controlled component with value
function ControlledExample() {
  const [value, setValue] = useState("");
  
  return (
    <TextareaAutosize
      value={value}
      onChange={(e) => setValue(e.target.value)}
      minRows={2}
      maxRows={8}
      placeholder="Enter your story..."
    />
  );
}

// With height change callback
function CallbackExample() {
  const handleHeightChange = (height: number, meta: TextareaHeightChangeMeta) => {
    console.log(`New height: ${height}px, Row height: ${meta.rowHeight}px`);
  };

  return (
    <TextareaAutosize
      onHeightChange={handleHeightChange}
      minRows={1}
      maxRows={5}
      placeholder="Type to see height changes..."
    />
  );
}

// With ref for direct access
function RefExample() {
  const textareaRef = React.useRef<HTMLTextAreaElement>(null);
  
  const focusTextarea = () => {
    textareaRef.current?.focus();
  };
  
  return (
    <div>
      <TextareaAutosize
        ref={textareaRef}
        placeholder="Click button to focus"
      />
      <button onClick={focusTextarea}>Focus Textarea</button>
    </div>
  );
}

// Performance optimized with caching
function CachedExample() {
  return (
    <TextareaAutosize
      cacheMeasurements={true}
      minRows={3}
      maxRows={15}
      placeholder="Large content with cached measurements..."
    />
  );
}

Row Configuration

Control the minimum and maximum size of the textarea using row-based constraints.

interface RowProps {
  /** Minimum number of rows to display (default: 1) */
  minRows?: number;
  /** Maximum number of rows before scrolling (default: Infinity) */
  maxRows?: number;
}
  • minRows: Sets the minimum height in rows - textarea won't shrink below this size
  • maxRows: Sets the maximum height in rows - textarea will scroll if content exceeds this size
  • Both props accept positive numbers, with maxRows defaulting to Infinity (no limit)

Height Change Callback

Receive notifications when the textarea height changes, useful for layout adjustments or analytics.

type HeightChangeHandler = (height: number, meta: TextareaHeightChangeMeta) => void;

interface TextareaHeightChangeMeta {
  /** The calculated height of a single row in pixels */
  rowHeight: number;
}

The callback provides:

  • height: New total height of the textarea in pixels
  • meta.rowHeight: Height of a single text row, useful for calculating row counts

Performance Optimization

Optional caching mechanism to improve performance when dealing with frequently changing content.

interface CachingOptions {
  /** Cache CSS measurements to avoid repeated DOM queries */
  cacheMeasurements?: boolean;
}

When cacheMeasurements is true:

  • CSS sizing data is cached after first calculation
  • Subsequent resizes use cached measurements instead of re-querying DOM
  • Improves performance for rapid content changes
  • Cache is automatically cleared when component unmounts

Style Constraints

The component accepts all standard textarea styles except maxHeight and minHeight, which conflict with the row-based sizing system.

type Style = Omit<
  NonNullable<React.TextareaHTMLAttributes<HTMLTextAreaElement>['style']>,
  'maxHeight' | 'minHeight'
> & {
  height?: number;
};

Important Style Notes:

  • maxHeight and minHeight CSS properties are not allowed - use maxRows and minRows props instead
  • height can be set as a number (interpreted as pixels) for initial sizing
  • All other CSS properties work normally (width, padding, border, etc.)
  • Component throws errors in development mode if restricted properties are used

Error Handling

The component performs validation in development mode and throws descriptive errors for common mistakes:

  • maxHeight style error: Thrown when style.maxHeight is provided - use maxRows prop instead
  • minHeight style error: Thrown when style.minHeight is provided - use minRows prop instead

These errors only occur in development builds to help catch configuration issues early.

Browser Compatibility

  • Modern Browsers: Full functionality with all features
  • Internet Explorer 9+: Supported with polyfills
  • Server-Side Rendering: Compatible - renders standard textarea on server, upgrades to auto-resize on client
  • Edge Cases: Graceful fallback to standard textarea behavior when JavaScript is disabled

Environment Detection

The component automatically detects the runtime environment:

  • Browser: Full auto-resize functionality with event listeners
  • Server/SSR: Renders static textarea without client-side features
  • Edge Runtime: Optimized build for edge computing environments