Created
January 23, 2014 06:56
-
-
Save pieterv/8574131 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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