In some cases, System has to provide suggestions to user while user typing. Sending request for each and every request to server will be overhead. So sending request to server when user finishes typing will give good performance. We can detect whether user typing or finished his typing by delaying the onChange event.
To Run Example Code
execute below commands
npm install
npm start
npm start
now open index.html in browser
Program
Observer below code. Here we are using setTimeout for giving delays
import React from 'react'; class TypeDetector extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { value:'' } } handleChange(evt) { if(this._timeout){ //if there is already a timeout in process cancel it clearTimeout(this._timeout); } const val = evt.target.value; this._timeout = setTimeout(()=>{ this._timeout = null; this.setState({ value:val }); },1000); } render() { return ( <div> <div> Value :: <b>{this.state.value}</b><br/><br/> </div> <input style={{width:'300px', padding:'5px'}} placeholder="Enter text here" onChange={this.handleChange}/> </div> ); } } TypeDetector.propTypes = { } TypeDetector.defaultProps = { } export default TypeDetector;
0 comments:
Post a Comment