Coder Social home page Coder Social logo

andarist / react-textarea-autosize Goto Github PK

View Code? Open in Web Editor NEW
2.1K 17.0 241.0 2 MB

<textarea /> component for React which grows with content

Home Page: http://andarist.github.io/react-textarea-autosize/

License: MIT License

HTML 4.00% JavaScript 8.97% TypeScript 87.03%
react react-component javascript

react-textarea-autosize's Introduction

npm version npm

react-textarea-autosize

Drop-in replacement for the textarea component which automatically resizes textarea as content changes. A native React version of the popular jQuery Autosize! Weighs around 1.3KB (minified & gzipped).

This module supports IE9 and above.

import TextareaAutosize from 'react-textarea-autosize';

// If you use CommonJS syntax:
// var TextareaAutosize = require('react-textarea-autosize').default;

React.renderComponent(
  <div>
    <TextareaAutosize />
  </div>,
  document.getElementById('element'),
);

Install

npm install react-textarea-autosize

Demo

https://andarist.github.io/react-textarea-autosize/

Props

Special props:

prop type description
maxRows number Maximum number of rows up to which the textarea can grow
minRows number Minimum number of rows to show for textarea
onHeightChange func Function invoked on textarea height change, with height as first argument. The second function argument is an object containing additional information that might be useful for custom behaviors. Current options include { rowHeight: number }.
cacheMeasurements boolean Reuse previously computed measurements when computing height of textarea. Default: false

Apart from these, the component accepts all props that are accepted by <textarea/>, like style, onChange, value, etc.

FAQ

How to focus

Get a ref to inner textarea:

<TextareaAutosize ref={(tag) => (this.textarea = tag)} />

And then call a focus on that ref:

this.textarea.focus();

To autofocus:

<TextareaAutosize autoFocus />

(all HTML attributes are passed to inner textarea)

How to test it with jest and react-test-renderer if you need ref

Because jest provides polyfills for DOM objects by requiring jsdom and react-test-renderer doesn't provide refs for rendered components out of the box (calling ref callbacks with null), you need to supply a mocked ref in your tests in you need it for your tests. You can do it like this (more can be read here):

const tree = renderer
  .create(<TextareaAutosize />, {
    createNodeMock: () => document.createElement('textarea'),
  })
  .toJSON();

react-textarea-autosize's People

Contributors

0m15 avatar andarist avatar andreyco avatar andreypopp avatar arnaudrinquin avatar chuntley avatar circlingthesun avatar clarityflowers avatar dashed avatar emdotem avatar emmenko avatar ganny26 avatar github-actions[bot] avatar greegus avatar jdalton avatar jenseng avatar kyleamathews avatar maciej-ka avatar mxschmitt avatar nikgraf avatar razh avatar rdil avatar rebelliard avatar rexxars avatar simenb avatar stevewillard avatar szyablitsky avatar torarnek avatar trun avatar vinpac 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-textarea-autosize's Issues

Compatibility with react-bootstrap?

I don't know the best way to approach this, so I'm just throwing it out there. If I'm already using react-bootstrap (http://react-bootstrap.github.io), what is the best way to approach using your code as well (given that react-bootstrap has their own textarea component)?

Just thought I'd ask in case anyone has already faced the same issue.

Doesn't work with React.addons.LinkedStateMixin

I get Uncaught Error: Invariant Violation: Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink. Makes sense, but it would be nice if this worked with the LinkedStateMixin as a "drop-in replacement".

update react's peer dependency version

since react v0.13.1 is out now, this module can't be installed due to the peerDependencies requirements. An update would be appreciated a lot (and judging by the 0.13 change log, no breaking changes should have happened here either)

Cheers!

Typing is garbled in IE11

Typing "Typing a test message" (and messing it up the second time 😸) with react/[email protected] and [email protected]:

react-textarea-autosize-ie11

The event handler isn't doing anything asynchronous:

  handleTextChange(e) {
    this.setState({text: e.target.value})
  },

This only seems to happen when the component is controlled - working around it by using it without a value prop. as that suits my current use case.

Performance issues on pages with lots of non-related components (if an id isn't given)

Hey folks,

We were experincing a lot of performance issues with this component on large pages (pages with a lot of other components, specifically). This is after we started using useCacheForDOMMeasurements.

After looking at the code here – it looks like if there's no id given, the component attempts to find the node using react-id, which is what was slowing it down.

The solution for us was to just assign an id (easy!) – but I thought it was worth writing up something here and making asking you to include it as part of the docs/README.

Cheers!

How to reset textarea's height?

How can I reset the textarea height, for example when user press Enter and we need to clear the textarea and reset its height accordingly?

scrollbars in Linux Chrome

I am seeing scrollbars in Linux Chrome (47.0.2526.106 (64-bit)). The height calculation seems to be just slightly off, so setting overflow: hidden is an acceptable workaround.

Wrong initial height

Initial height is '15px', after I type any symbol, it is set to '26px'. In debugger I see hidden textarea uses initial font-family 'monospace' and after typing any symbol it is changed to 'Helvetica'. I couldn't find a workaround yet.

Wrong height using box-sizing: border-box.

textarea {
    height: 32px;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

Computed height equals to 34px. In this case, it should equal to 32px, since box-sizing: border-box is applied.

bower.io package

As mostly a frontend utility, a bower package would be very useful.

React 0.14 warning - style object previously mutated

Getting this error:
Warning: textareawas passed a style object that has previously been mutated. Mutatingstyleis deprecated. Consider cloning it beforehand. Check therenderofTextareaAutosize. Previous style: {height: NaN}. Mutated style: {height: NaN}.

Looks like #70 will solve it, but wanted to have a searchable issue in case anyone else is seeing this.

react 0.14.0-rc1

wanted to check to see if the package.json could be updated to support react 0.14

word-wrap and overflow-x not taken into account

Right now if you set word-wrap or overflow-x to a value different from those set in HIDDEN_TEXTAREA_STYLE you'll end up with a text area that does not match its contents. Going to try and work on a pull request for this if I can figure it out.

Resize on a Textarea with `text-indent` defined doesn't work well

Hello! I'm having trouble trying to use react-textarea-autosize on a textarea with text-indent defined. It resizes only when the second row's witdh is bigger than the text-indent value.
It occurs because the text-indent places a space at the start of the textarea and the hidden textarea doesn't have this property set, so causing the calculation to be wrong.
How could I solve this?

Tests

Are any available for this?

Getting HTML element ref

Is it possible to get the element ref off of a textarea?

When doing something like this:

<TextArea ref='content' />

I'd expect to be able to do something like this:

this.refs.content.refs.content

which would get me the ref of the HTML element.

Unfortunately this.refs.content.refs returns an empty object.

In order to get the ref of the HTML element I have to do something like this:

this.refs.content._rootDOMNode

Let me know if I'm doing something wrong. Otherwise I'd like to figure out a way to get refs to work properly or make _rootDOMNode public.

Wrong calculation of Height

The method calculateNodeHeight() calculates height for one row using hiddenTextarea.scrollHeight.
The property will also include any padding that is applied. And when to calculate height for n rows, the value is multiplied by n, and as a result the padding gets multiplied as many times.
Is this intended?

Number of rows shown is wrong in Firefox

This difference only surfaces at unrealistically small font sizes (used in a test case).

maxRows={3} and style={{ lineHeight: 1, fontSize: 10, border: 0, boxSizing: 'border-box' }}

In Chrome the textarea shows 3 rows, height of 33px

In Firefox the textarea shows 4 rows, height of 39px

What is the use case for `onHeightChange` callback?

(Context: I am playing around with using this in https://github.com/necolas/react-native-web/)

What do you see as the use case for this? The callback takes a height, which seems to be the CSS height (respects border-box) rather than the layout height of the element.

So to implement onLayout I need to re-query the DOM anyway, to get the outer height/width/offset. But one thing I cannot do easily is infer the number of rows. That might be quite useful to pass to the callback.

transfer className property to textarea

or generally transfer all possible props to real textarea component.

import React from "'react";
import Textarea from "'react-textarea-autosize";

React.renderComponent(
  <Textarea onFocus={this.handleFocus} onBlur={this.handleBlur} autofocus></Textarea>,
  document.body
)

Non synchronous value sets break cursor position

hi! thanks for the great component,

If you are controlling the component value but don't update the value immediately, the textarea will render a few times between resetting the old value and moving the cursor to the end of the textarea (so start typing in the middle of some text).

minimal reproducible code below:

<Textarea 
   value={(this.state || {}).value} 
   onChange={ e => {
     let value = e.target.value;
     setTimeout(() => this.setState({ value }))
  }}
/>

You might ask why update the value asynchronously, and that would be a valid question! Some times you don't have a choice, the upper setState may be async, and if you are managing state across Portals/Subtrees/Layers?Whatever-the-current-term-is the additional ReactDom.render() is async generally.

I have poked through the code to try and see If anything immediately stood out as the cause of the issue but didn't see anything (due almost certainly to my ignorance), perhaps its due to triggering _resizeComponent in the onChange() handler, maybe it's related to: facebook/react#1698 (tho that is clearly been fixed).

and not to hawk my own wares, but perhaps explicitly managing the controlled/uncontrolled state of the input might help, we use: https://github.com/jquense/uncontrollable for such things.

`rows` attribute not respected

<Textarea rows=4/> gets set to a height of one row.

Haven't grokked the new code yet sufficiently to see how to fix this. I'll get to this next week unless one of you want to get to it first.

event.keycode issue.

how to handle event.keycode at onChange?

if i try to added onKeyDown event and then onChange will not be fired. any idea?

"Cannot read property 'value' of undefined" when re-exported + hot-loader

I have one module where I just collect all the components I need and then reexport them like so

export TextArea from 'react-textarea-autosize'

as soon as I try to import it react-textarea-autosize throws. It tries to get value but it's obviously not mounted yet.
I assume I'm doing something weird and react-hot-loader is not enjoying it.
Ideas? @gaearon
screen shot 2015-10-08 at 22 44 47

Element type is invalid: expected a string on a simple instanciation. Documentation is incorrect on how to use this component

Working use is either :

var Textarea = require('react-textarea-autosize').default;

or

import TextareaAutosize from 'react-textarea-autosize';

The actual declaration in the documentation trigger an error :

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of YourComponent

and

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of YourComponent

Doesn't work with CSSTransitionGroup animations

I'm using a CSSTransitionGroup to perform a page transition to a page with the textarea-autosize component. The animation won't run if I don't remove the call to _resizeComponent in ComponentDidMount.

Not entirely sure what's causing it yet.

findDOMNode

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

able to update for 0.14.0-rc1? :)

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.