insomnia/app/components/base/DebouncingInput.js

56 lines
1.2 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 {
_valueChanged (e) {
2016-03-20 23:20:00 +00:00
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 () {
2016-03-20 23:20:00 +00:00
this.refs.input.value = this.props.initialValue || this.props.value || '';
}
componentDidMount () {
this._updateValueFromProps()
2016-03-20 23:20:00 +00:00
}
2016-03-20 23:20:00 +00:00
componentDidUpdate () {
this._updateValueFromProps()
}
focus () {
this.refs.input.focus();
2016-03-20 23:20:00 +00:00
}
render () {
const {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"
onChange={this._valueChanged.bind(this)}
2016-03-20 23:20:00 +00:00
/>
)
}
}
2016-03-23 05:26:27 +00:00
DebouncingInput.propTypes = {
2016-03-20 23:20:00 +00:00
onChange: PropTypes.func.isRequired,
value: PropTypes.string.isRequired,
debounceMillis: PropTypes.number
2016-03-20 23:20:00 +00:00
};
2016-03-23 05:26:27 +00:00
export default DebouncingInput;