insomnia/app/components/base/DebouncingInput.js

56 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-03-20 23:20:00 +00:00
import React, {Component, PropTypes} from 'react';
const DEFAULT_DEBOUNCE_MILLIS = 300;
2016-03-23 05:26:27 +00:00
/**
* Input that only fire onChange() after the user stops typing
*/
class DebouncingInput extends Component {
2016-03-20 23:20:00 +00:00
valueChanged (e) {
if (!this.props.onChange) {
return;
}
// Surround in closure because callback may change before debounce
clearTimeout(this._timeout);
((value, cb, debounceMillis = DEFAULT_DEBOUNCE_MILLIS) => {
this._timeout = setTimeout(() => cb(value), debounceMillis);
})(e.target.value, this.props.onChange, this.props.debounceMillis);
}
updateValueFromProps() {
this.refs.input.value = this.props.initialValue || this.props.value || '';
}
componentDidMount () {
this.updateValueFromProps()
}
componentDidUpdate () {
this.updateValueFromProps()
}
render () {
2016-04-09 01:14:25 +00:00
const {initialValue, value, ...other} = this.props;
2016-03-20 23:20:00 +00:00
return (
<input
2016-04-09 01:14:25 +00:00
{...other}
2016-03-20 23:20:00 +00:00
ref="input"
type="text"
2016-03-21 05:47:49 +00:00
className={this.props.className}
2016-03-20 23:20:00 +00:00
initialValue={initialValue || value}
onChange={this.valueChanged.bind(this)}
/>
)
}
}
2016-03-23 05:26:27 +00:00
DebouncingInput.propTypes = {
2016-03-20 23:20:00 +00:00
onChange: PropTypes.func.isRequired,
initialValue: PropTypes.string,
debounceMillis: PropTypes.number,
value: PropTypes.string
};
2016-03-23 05:26:27 +00:00
export default DebouncingInput;