-
-
Save mandadimuralidharreddy/60e1e2a50d88aed7ce1a09865f901dfa to your computer and use it in GitHub Desktop.
ReactJS: Input fire onChange when user stopped typing (or pressed Enter key)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import TextField from 'components/base/TextField'; | |
const WAIT_INTERVAL = 1000; | |
const ENTER_KEY = 13; | |
export default class TextSearch extends Component { | |
constructor(props) { | |
super(); | |
this.state = { | |
value: props.value | |
}; | |
} | |
componentWillMount() { | |
this.timer = null; | |
} | |
handleChange(value) { | |
clearTimeout(this.timer); | |
this.setState({ value }); | |
this.timer = setTimeout(::this.triggerChange, WAIT_INTERVAL); | |
} | |
handleKeyDown(e) { | |
if (e.keyCode === ENTER_KEY) { | |
::this.triggerChange(); | |
} | |
} | |
triggerChange() { | |
const { value } = this.state; | |
this.props.onChange(value); | |
} | |
render() { | |
const { className } = this.props; | |
return ( | |
<TextField | |
className={className} | |
placeholder={l('Search')} | |
value={this.state.value} | |
onChange={::this.handleChange} | |
onKeyDown={::this.handleKeyDown} | |
/> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment