Skip to content

Instantly share code, notes, and snippets.

@moodysalem
Last active March 17, 2016 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moodysalem/52601c137109cf87434b to your computer and use it in GitHub Desktop.
Save moodysalem/52601c137109cf87434b to your computer and use it in GitHub Desktop.
A React TextArea component that automatically resizes to its content
React.createClass({
displayName: 'Autoresizing TextArea',
propTypes: {
height: React.PropTypes.number.isRequired,
onChangeHeight: React.PropTypes.func.isRequired
},
getDefaultProps: function () {
return {
height: 0
};
},
componentDidMount: function () {
this.calculateHeight();
},
componentDidUpdate: function () {
this.calculateHeight();
},
calculateHeight: function () {
const hiddenScrollHeight = this.refs.hidden.scrollHeight;
if (typeof hiddenScrollHeight !== 'number') {
return;
}
if (hiddenScrollHeight !== this.props.height) {
this.props.onChangeHeight(hiddenScrollHeight);
}
},
render: function () {
return React.DOM.span({}, [
// render the same textarea twice, once with no height
React.DOM.textarea(Object.assign({}, this.props, {
key: 'visible',
style: Object.assign({}, this.props.style, { resize: 'none', height: this.props.height })
})),
React.DOM.textarea(Object.assign({}, this.props, {
key: 'hidden',
ref: 'hidden',
// used only to calculate the height of the input
style: Object.assign({}, this.props.style, {
resize: 'none', visibility: 'hidden', position: 'absolute', height: 0
})
}))
]);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment