Skip to content

Instantly share code, notes, and snippets.

@felipeochoa
Created May 15, 2017 13:32
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 felipeochoa/1ada203ea68dce134d920b170bdd13cc to your computer and use it in GitHub Desktop.
Save felipeochoa/1ada203ea68dce134d920b170bdd13cc to your computer and use it in GitHub Desktop.
import React from 'react';
import autosize from 'autosize';
class AutoTextarea extends React.Component {
constructor(props) {
super(props);
this.refHandler = this.refHandler.bind(this);
this.textarea = null;
}
refHandler(node) {
if (node === this.textarea) return;
if (this.textarea) {
autosize.destroy(this.textarea);
}
if (node) {
autosize(node);
}
this.textarea = node;
}
componentDidUpdate(prevProps) {
if (prevProps.value !== this.props.value) {
autosize.update(this.textarea);
}
}
focus() {
this.textarea.focus();
}
resize() {
autosize.update(this.textarea);
}
render() {
const {...otherProps} = this.props;
otherProps.rows = otherProps.rows === undefined ? "1" : otherProps.rows;
return (
<textarea ref={this.refHandler} {...otherProps}/>
);
}
}
export default AutoTextarea;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment