Skip to content

Instantly share code, notes, and snippets.

@pieterv
Created January 23, 2014 06:56
Show Gist options
  • Save pieterv/8574131 to your computer and use it in GitHub Desktop.
Save pieterv/8574131 to your computer and use it in GitHub Desktop.
/** @jsx React.DOM */
'use strict';
// Libs
var React = require( 'react' );
var AutoGrowTextarea = React.createClass( {
getInitialState: function() {
return {
contentHeight: 0
};
},
render: function() {
var textareaHeight = { height: this.state.contentHeight };
var displayTextarea = this.transferPropsTo(
<textarea ref="displayTextarea" style={textareaHeight} />
);
return (
<div>
{this.renderMeasurableTextarea()}
{displayTextarea}
</div>
);
},
renderMeasurableTextarea: function() {
var holderStyle = { opacity: 0, height: 1, overflow: 'hidden' };
var measurableTextarea = this.transferPropsTo(
<textarea ref="measurableTextarea" onChange={null} autoFocus={false} />
);
return (
<div style={holderStyle}>
{measurableTextarea}
</div>
);
},
componentDidMount: function() {
this.updateContentHeight();
},
componentDidUpdate: function( prevProps ) {
if ( this.props.value !== prevProps.value ) {
this.updateContentHeight();
}
},
updateContentHeight: function() {
var borderTopBottomWidth = 0;
if ( 'getComputedStyle' in window ) {
var computedStyle = window.getComputedStyle( this.refs.displayTextarea.getDOMNode(), null );
borderTopBottomWidth = parseInt( computedStyle.getPropertyValue( 'border-top-width' ), 10 ) +
parseInt( computedStyle.getPropertyValue( 'border-bottom-width' ), 10 );
}
this.setState( { contentHeight: this.refs.measurableTextarea.getDOMNode().scrollHeight + borderTopBottomWidth } );
}
} );
module.exports = AutoGrowTextarea;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment