Skip to content

Commit

Permalink
Add autoresize to multiline inputs
Browse files Browse the repository at this point in the history
This fixes #278
  • Loading branch information
SimonSelg authored and javivelasco committed Jun 25, 2016
1 parent bde7e4c commit 5b97b95
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
34 changes: 34 additions & 0 deletions components/input/Input.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,44 @@ const factory = (FontIcon) => {
type: 'text'
};

componentDidMount () {
window.addEventListener('resize', this.handleAutoresize);
}

componentWillReceiveProps (nextProps) {
if (!this.props.multiline && nextProps.multiline) {
window.addEventListener('resize', this.handleAutoresize);
} else if (this.props.multiline && !nextProps.multiline) {
window.removeEventListener('resize', this.handleAutoresize);
}
}

componentWillUnmount () {
window.removeEventListener('resize', this.handleAutoresize);
}

handleChange = (event) => {
if (this.props.multiline) {
this.handleAutoresize();
}
if (this.props.onChange) this.props.onChange(event.target.value, event);
};

handleAutoresize = () => {
const element = this.refs.input;
// compute the height difference between inner height and outer height
const style = getComputedStyle(element, null);
let heightOffset = 0;
if (style.boxSizing === 'content-box') {
heightOffset = -(parseFloat(style.paddingTop) + parseFloat(style.paddingBottom));
} else {
heightOffset = parseFloat(style.borderTopWidth) + parseFloat(style.borderBottomWidth);
}
// resize the input to its content size
element.style.height = 'auto';
element.style.height = `${element.scrollHeight + heightOffset}px`;
}

blur () {
this.refs.input.blur();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class InputTest extends React.Component {
state = { name: '', phone: '', email: '', hint: '' };
state = { name: '', phone: '', multiline: '', email: '', hint: '' };

handleChange = (name, value) => {
this.setState({...this.state, [name]: value});
Expand All @@ -10,6 +10,7 @@ class InputTest extends React.Component {
<section>
<Input type='text' label='Name' name='name' value={this.state.name} onChange={this.handleChange.bind(this, 'name')} maxLength={16 } />
<Input type='text' label='Disabled field' disabled />
<Input type='text' multiline label='Multiline' onChange={this.handleChange.bind(this, 'multiline')} />
<Input type='email' label='Email address' icon='email' value={this.state.email} onChange={this.handleChange.bind(this, 'email')} />
<Input type='tel' label='Phone' name='phone' icon='phone' value={this.state.phone} onChange={this.handleChange.bind(this, 'phone')} />
<Input type='text' value={this.state.hint} label='Required Field' hint='With Hint' required onChange={this.handleChange.bind(this, 'hint')} icon={<span>J</span>} />
Expand Down

0 comments on commit 5b97b95

Please sign in to comment.