Skip to content

Instantly share code, notes, and snippets.

@xamedow
Forked from laytong/bad-input.jsx
Created February 8, 2018 15:22
Show Gist options
  • Save xamedow/8afe2ccafefc237d4184f1ec35c26e41 to your computer and use it in GitHub Desktop.
Save xamedow/8afe2ccafefc237d4184f1ec35c26e41 to your computer and use it in GitHub Desktop.
How to debounce your inputs for super fast react/redux components
import React, {Component, PropTypes} from 'react';
class BadInputComponent extends Component {
static propTypes = {
text = PropTypes.string.isRequired,
updateText = PropTypes.func.isRequired,
};
render() {
return (
<input onChange={this.handleTextChange} value={this.state.text} />
);
}
handleTextChange = (e) => {
this.props.updateText(e.target.value)
};
}
export default BadInputComponent;
import React, {Component, PropTypes} from 'react';
import debounce from 'lodash/debounce';
class DebouncedInputComponent extends Component {
static propTypes = {
text = PropTypes.string.isRequired,
updateText = PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
text: '',
};
}
componentDidMount() {
this.sendTextChange = debounce(this.sendTextChange, 500);
this.setState({text:this.props.text});
}
render() {
return (
<input onChange={this.handleTextChange} value={this.state.text} />
);
}
handleTextChange = (e) => {
this.setState({text: e.target.value});
this.sendTextChange(e.target.value.trim())
};
sendTextChange = (text) => {
this.props.updateText(text);
};
}
export default DebouncedInputComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment