Trigger Event When User Finishes Typing Instead of onChange Using ReactJS

Datetime:2016-08-23 00:10:11          Topic: React           Share

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.

Click here to see DEMO Download code

To Run Example Code

execute below commands

npm install

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;




About List