Git Product home page Git Product logo

react-autosize-textarea's Introduction

React Autosize Textarea

A light replacement for built-in <textarea /> component which automatically adjusts its height to match the content.

NB: It does not require any polyfill

import ReactDOM from 'react-dom';
import TextareaAutosize from 'react-autosize-textarea';

ReactDOM.renderComponent(
  <TextareaAutosize {...textareaProps} onResize={(e) => {}} />,
  document.body
);

Install

npm install --save react-autosize-textarea
yarn add react-autosize-textarea

Demo

Live Examples

Usage

TextareaAutosize is perfectly compatible with ReactJS default one, so to get started you can simply replace any <textarea></textarea> with <TextareaAutosize></TextareaAutosize>. It's that easy :)

Props

You can pass any prop you're allowed to use with the default React textarea (valueLink too).

In addition to them, TextareaAutosize comes with some optional custom props to facilitate its usage:

Name Type Default Description
onResize Function optional. Called whenever the textarea resizes
rows Number optional. Minimum number of visible rows
maxRows Number optional. Maximum number of visible rows
async Boolean false optional. Initialize autosize asynchronously. Enable it if you are using StyledComponents. This is forced to true when maxRows is set. Async initialization will make your page "jump" when the component appears, as it will first be rendered with the normal size, then resized to content.
ref Function optional. Ref to the DOM node

onResize

Sometimes you may need to react any time TextareaAutosize resizes itself. To do so, you should use the optional callback onResize which will be triggered at any resize with the autosize:resized event object:

function onResize(event) {
  console.log(event.type); // -> "autosize:resized"
}

<TextareaAutosize onResize={onResize} />

Set min/max height

You can set minHeight and maxHeight through CSS or inline-style as usual:

<TextareaAutosize style={{ minHeight: 20, maxHeight: 80 }} /> // min-height: 20px; max-height: 80px;

NB: you may need to take into account borders and/or padding.

In addition to minHeight, you can force TextareaAutosize to have a minimum number of rows by passing the prop rows:

<TextareaAutosize rows={3} /> // minimun height is three rows

In addition to maxHeight, you can force TextareaAutosize to have a maximum number of rows by passing the prop maxRows:

<TextareaAutosize maxRows={3} /> // maximum height is three rows

Refs to DOM nodes

In order to manually call textarea's DOM element functions like focus() or blur(), you need a ref to the DOM node.

You get one by using the prop ref as shown in the example below:

class Form extends React.Component {
  constructor() {
    this.textarea = React.createRef()
  }
  
  componentDidMount() {
    this.textarea.current.focus();
  }

  render() {
    return (
      <TextareaAutosize ref={this.textarea} />
    );
  }
}

Browser Compatibility

Chrome Firefox IE Safari Android
Yes Yes 9+ Yes 4+

Credits

This module is based on the very popular autosize script written by Jack Moore.

Check out his repo or website for more documentation.

react-autosize-textarea's People

Contributors

alex-ketch avatar ascariandrea avatar efedorenko avatar francescocioria avatar gabro avatar gcanti avatar giogonzo avatar humphreybc avatar iktakahiro avatar jnsdls avatar lucacioria avatar pajn avatar renchap avatar ricardojoaoreis avatar ronny avatar taraojo avatar veej avatar vkalinichev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-autosize-textarea's Issues

Wrong initial height when using StyledComponents

description

The initial height is always rendered wrongly when using StyledComponents

how to reproduce

  • {optional: describe steps to reproduce bug}

specs

StyledComponents adds the style asynchronously while we run autosize immediately in componentDidMount -> let's run it with a setTimeout as we're already doing when maxRows props is passed

misc

{optional: other useful info}

How to detect keystrokes ?

Hello!

I was wondering how can I detect e.which for example inside onChange.
So far, it returns undefined.

Thanks

Typescript: compile time error for native textarea attributes

Hello, thanks for support Typescript out-of-box.

But i have a trouble:

error TS2339: Property 'name' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<TextareaAutosizeProps, ComponentState>> ...

from this code:

import * as React from 'react';
import TextareaAutosize from 'react-autosize-textarea';

interface Props {
    onChange: React.EventHandler<React.ChangeEvent<HTMLTextAreaElement>>;
    value: string;
}

export default class Textarea extends React.Component<Props, {}> {
  render() {
    return (
      <TextareaAutosize
         className="textarea__control"
         name="message"
         placeholder="Your message"
         onChange={this.props.onChange}
         value={this.props.value}
      />
    );
  }
}

I look at react-autosize-textarea.d.ts and think that have an error:

/// <reference types="react" />

import * as React from 'react';

--- export interface TextareaAutosizeProps extends React.HTMLAttributes<HTMLTextAreaElement> {
+++ export interface TextareaAutosizeProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  onResize?: (e: React.SyntheticEvent<Event>) => void,
  // rows is already typed in `React.HTMLAttributes<HTMLTextAreaElement>`
  maxRows?: number,
  innerRef?: (textarea: HTMLTextAreaElement) => void
}

declare const TextareaAutosize: React.ComponentClass<TextareaAutosizeProps>;
export default TextareaAutosize

React.HTMLAttributes doesn't have a textarea attributes, such as name, placeholder, ...

I replaced React.HTMLAttributes wtih React.TextareaHTMLAttributes and it work fine.

Last release broke support for React < 15.5

description

In the last release we switched from React.PropTypes to the external library prop-types. Unfortunately we forgot to add prop-types to the required dependencies making that change a serious breaking change that would break also production environments!

Once React@16 is published we should revert this issue and release a breaking version

how to reproduce

  • {optional: describe steps to reproduce bug}

specs

add prop-types to required environments and release a patch.

misc

{optional: other useful info}

getting data out of textarea

I must be missing something very obvious, but I can t seem to get the text out of the textarea_ref.value seems empty for me ...

sorry again if this is a really stupid question

Resize component when inner textarea value is cleared

Given

<TextareAutosize innerRef={c=>{refTextarea=c}} />
<button onClick={clearTextarea}>Clear</button>

...

function clearTextarea() {
  refTextarea.value = ''
}

When you click the 'Clear' button, the content of the inner ref textarea is replaced with the empty string, but the height of the outer TextareaAutosize component retains whatever height it had ahead of the content clear.

wrong max height when using maxRows and boxSizing "border-box"

description

If the textarea has box-sizing: border-box and some padding, the max height computed to have the desired maxRows is wrong.

how to reproduce

  • <TextareaAutosize style={{ boxSizing: 'border-box', padding: 10 }} maxRows={3} />

specs

if this.props.maxRows then pass { boxSizing: 'content-box' } to the textarea by default as style.
this inline style should be overridable by this.props.style

misc

{optional: other useful info}

Ref issue & Compatibility with React 15.4.0

description

Since React15 refs should be used with callbacks

how to reproduce

  • {optional: describe steps to reproduce bug}

specs

  • store textarea ref as this.textarea with callback
  • remove getTextareaDOMNode

misc

{optional: other useful info}

Getting a lot of Null is not an object in production

TypeError: null is not an object (evaluating 'n.textarea.dispatchEvent')
1
File "webpack:///./~/react-autosize-textarea/lib/TextareaAutosize.js" line 55 col 1 in a
return _this.textarea.dispatchEvent(event);

In Chrome 55 UI Webview , Mobile Safari UI Webview 10, Mobile iOS Webview 10.

All these are variants of the same iOS Safari 10 engine.

TS Types can't be found by VSCode/tsc

description

TS Types can't be found by VSCode/tsc

how to reproduce

  • {optional: describe steps to reproduce bug}

specs

Add "typings" declaration pointer to package.json

misc

{optional: other useful info}

Continuous integration is failing

11-Jun-2015 16:10:29    Executing command bash -c CONTINUOUS_INTEGRATION=1 npm test || true && ./node_modules/eslint/bin/eslint.js src -f compact > eslint-errors
11-Jun-2015 16:10:29    
11-Jun-2015 16:10:29    > [email protected] test /data
11-Jun-2015 16:10:29    > ./node_modules/karma/bin/karma start
11-Jun-2015 16:10:29    
11-Jun-2015 16:10:30    INFO [karma]: Karma v0.12.36 server started at http://localhost:9876/
11-Jun-2015 16:10:30    INFO [launcher]: Starting browser Chrome
11-Jun-2015 16:10:32    WARN [web-server]: 404: /favicon.ico
11-Jun-2015 16:10:32    INFO [Chrome 43.0.2357 (Linux 0.0.0)]: Connected on socket 2cymhpNLzU436S1Y9TWA with id 56835897
11-Jun-2015 16:10:33    7 XSELINUXs still allocated at reset
11-Jun-2015 16:10:33    SCREEN: 0 objects of 256 bytes = 0 total bytes 0 private allocs
11-Jun-2015 16:10:33    DEVICE: 0 objects of 96 bytes = 0 total bytes 0 private allocs
11-Jun-2015 16:10:33    CLIENT: 0 objects of 136 bytes = 0 total bytes 0 private allocs
11-Jun-2015 16:10:33    WINDOW: 0 objects of 32 bytes = 0 total bytes 0 private allocs
11-Jun-2015 16:10:33    PIXMAP: 2 objects of 16 bytes = 32 total bytes 0 private allocs
11-Jun-2015 16:10:33    GC: 4 objects of 16 bytes = 64 total bytes 0 private allocs
11-Jun-2015 16:10:33    CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
11-Jun-2015 16:10:33    TOTAL: 7 objects, 104 bytes, 0 allocs
11-Jun-2015 16:10:33    2 PIXMAPs still allocated at reset
11-Jun-2015 16:10:33    PIXMAP: 2 objects of 16 bytes = 32 total bytes 0 private allocs
11-Jun-2015 16:10:33    GC: 4 objects of 16 bytes = 64 total bytes 0 private allocs
11-Jun-2015 16:10:33    CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
11-Jun-2015 16:10:33    TOTAL: 7 objects, 104 bytes, 0 allocs
11-Jun-2015 16:10:33    4 GCs still allocated at reset
11-Jun-2015 16:10:33    GC: 4 objects of 16 bytes = 64 total bytes 0 private allocs
11-Jun-2015 16:10:33    CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
11-Jun-2015 16:10:33    TOTAL: 5 objects, 72 bytes, 0 allocs
11-Jun-2015 16:10:33    1 CURSORs still allocated at reset
11-Jun-2015 16:10:33    CURSOR: 1 objects of 8 bytes = 8 total bytes 0 private allocs
11-Jun-2015 16:10:33    TOTAL: 1 objects, 8 bytes, 0 allocs
11-Jun-2015 16:10:33    1 CURSOR_BITSs still allocated at reset
11-Jun-2015 16:10:33    TOTAL: 0 objects, 0 bytes, 0 allocs
11-Jun-2015 16:10:33    npm ERR! Test failed.  See above for more details.
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/cyrillic, removing from list!
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/100dpi/:unscaled, removing from list!
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/75dpi/:unscaled, removing from list!
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/Type1, removing from list!
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/100dpi, removing from list!
11-Jun-2015 16:10:33    [dix] Could not init font path element /usr/share/fonts/X11/75dpi, removing from list!
11-Jun-2015 16:10:34    Failing task since return code of [/usr/bin/docker run --volume /volumes/bamboo-server/xml-data/build-dir/1736705/WEB-RTA-JOB1:/data 

JSX element type 'TextareaAutosize' is not a constructor function for JSX elements.

The following error is thrown when trying to compile a project using the autosize textarea component with Typescript 2.3.4:
error TS2605: JSX element type 'TextareaAutosize' is not a constructor function for JSX elements.

The fix is simple:

// export default class TextareaAutosize extends React.Component<TextareaAutosizeProps, void> {}
export default class TextareaAutosize extends React.Component<TextareaAutosizeProps, {}> {}

Can this be included in the next version?

Error in React 16: innerRef passed to the DOM element.

proxyConsole.js:56 Warning: React does not recognize the `innerRef` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `innerref` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

How to reproduce: Just render the element in React 16.

`this.dispatchEvent(UPDATE)` called too often

description

this.dispatchEvent(UPDATE) should be called only when TextareaAutosize receives an unexpected props.value while, at the moment, it's called every time props.value is different from prevProps.value which happens after every onChange

how to reproduce

  • {optional: describe steps to reproduce defect}

specs

  • in this.onChange cache the current value as this.currentValue
  • in componentDidUpdate call this.dispatchEvent(UPDATE); only if props.value is different from this.currentValue

misc

{optional: other useful info}

Max Rows

Hey,

It'd be awesome to have a "max-rows" prop.

Thank you for your work.

Resize horizontal inline style overrides CSS styles

I'm passing resize: none through as CSS to disable the drag handle in the bottom right of the textarea, but it's being overridden by an inline style resize: horizontal. After a short investigation, I think this is coming from autosize line 53.

Here's some reproduction code:

import * as React from "react";
import TextareaAutosize from "react-autosize-textarea";
import { style } from "typestyle";

export class ResizeDemo extends React.PureComponent {
  public render() {
    return <TextareaAutosize className={textAreaClassName} />;
  }
}

const textAreaClassName = style({
  resize: "none"
});

typescript support

requirements

add typescript support

specs

{optional: describe technical specs to implement this feature, if not obvious}

misc

{optional: other useful info}

Upgrade peerDeps to react & react-dom 16

requirements

Add support for react & react-dom v16.x to remove the warnings when installing the dependencies

specs

{optional: describe technical specs to implement this feature, if not obvious}

misc

{optional: other useful info}

Max rows not working with text without breakline char

Max-rows not work with long strings:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga aspernatur ut ullam rem ipsam. Fuga illo velit sapiente necessitatibus, voluptatum earum at quo magnam impedit, molestias aliquid, voluptates, sit odit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga aspernatur ut ullam rem ipsam. Fuga illo velit sapiente necessitatibus, voluptatum earum at quo magnam impedit, molestias aliquid, voluptates, sit odit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga aspernatur ut ullam rem ipsam. Fuga illo velit sapiente necessitatibus, voluptatum earum at quo magnam impedit, molestias aliquid, voluptates, sit odit. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fuga aspernatur ut ullam rem ipsam. Fuga illo velit sapiente necessitatibus, voluptatum earum at quo magnam impedit, molestias aliquid, voluptates, sit odit.

Bug example:
image

How to hide the vertical scroll bar when maxRows is defined

Long Story Short

I'm trying to hide the vertical scroll bar when the number of lines exceeds maxRows. For example I have foo\nbar in the textarea and maxRows is set to 1. To do so I pass overflow: "hidden" to the style attribute of the component. Apparently this attribute in particular is ignored. I tried also overflowY: "hidden" without success.

Expected Behavior

The style attribute overrides also the overflow* attributes.

Actual Behavior

The component ignores the specified overflow* style attributes.

Use Case

I'm building a component that is a one-line field. When it gets focus, I want this component to expand to its full size. When I leave, I want this component to get back to one-line only [edit] without a scroll bar.

TextareaAutosize.Props type annotations are not working in VSCode

description

TextareaAutosize.Props type annotations are not working in VSCode

how to reproduce

  • TextareaAutosize.Props['maxRows'] does not show the annotation "Maximum number of visible rows"

specs

use supported format for annotations

misc

{optional: other useful info}

Remove react-tcomb

One of the issues I currently have is that react-autosize-textarea includes react-tcombe, and my final production build has an extra 53kb just from t-combe.

Can we remove it?

Is there a way to control Alignment?

I've build an app that uses the component multiple times. Great work!
I personally use the app with two languages - English, and another language which is aligned to the right. By default the text-areas align to the left. If I want to change and align them to the right I can simply press right CTR+Shift. When the screen re-renders it is aligned to the left again. I want to somehow control the alignment - recognize if a user chooses to align in a certain way, and save it to the state. How can I recognize how the user chooses to align the text, or if he presses right or left CTR+Shift? And how do I change the text-area so the alignment is controlled?

linked module fails to load in webpack

Hi,

I tried to link the react-autosize-textarea module in my project (npm link) to debug some issue but it failed with the error that lib cannot be found. I traced the failure to the react-autosize-textarea/index.js where require() is called without the leading './' which causes the loader to search for lib in node_modules. Once the leading './' is added everything seems to work.

Use `PureComponent`

requirements

extend PureComponent instead of Component as it usually increase performance and it should cause no trouble on a leaf component like TextareaAutosize

specs

{optional: describe technical specs to implement this feature, if not obvious}

misc

{optional: other useful info}

remove react 0.14 warnings

requirements

remove this warning:

Warning: React.findDOMNode is deprecated. Please use ReactDOM.findDOMNode from require('react-dom') instead.

specs

  • push a breaking change and update peerDependencies
  • tag current master as react-0.13

Rename lib to src?

AFAIK it's the standard name for the folder containing ES6 source code (generally lib contains ES5)

Add prop `innerRef` to access textarea DOM node

requirements

As gaeron said here, sooner or later ReactDOM.findDOMNode will be deprecated and it will be apt to each component to decide if the user will be able or not to access the DOM node by its standard prop API.

We should add a prop innerRef: t.maybe(t.Function) that is called with the ref to the DOM node if it exists.

specs

{optional: describe technical specs to implement this feature, if not obvious}

misc

{optional: other useful info}

Textarea is slow on safari

description

The textarea input is lagged on Safari.

how to reproduce

  • {optional: describe steps to reproduce defect}

specs

  • debounce this.dispatchEvent

misc

{optional: other useful info}

Version 1.0.0 not found?

With version 1.0.0 I'm getting:

Uncaught (in promise) Error: Cannot find module 'react-autosize-textarea' 

When trying to import the package.

Any ideas?

after #42 the linter of atom gives an error after every edit

description

after #42 the linter of atom gives an error after every edit

how to reproduce

  • open this project in atom with eslint linter plugin configured
  • make any change to the code

specs

{optional: describe a possible fix for this bug, if not obvious}

misc

{optional: other useful info}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.