javascript - Input validation setTimeout in ReactJS -


i have component renders classname="error" or classname="" depending on whether input valid or not. way in css can .error { background: red; }. validity of input determined isvalidnumber(..) function. however, right problem i'm having validation too instantaneous. if input invalid instantly renders "error" class name annoying ux issue. have delay of sort not have class "error" instantly, maybe 0.5 seconds nice.

demo of component. input valid on things "2.3 billion", or "1 trillion", or "203239123", not "2 sheeps" or "mountain". github repo

here component far. can see tried using settimeout setstate({ isvalid: isvalid }) function whenever isvalid false.

export default class numberinput extends react.component {     constructor(props) {         super(props);         this.state = {             value: "",             isvalid: false         };     }     setisvalid(isvalid) {         this.setstate({ isvalid: isvalid })     }     handlechange(event) {         var value = event.target.value         this.setstate({ value: event.target.value })          var isvalid = isvalidnumber(value)         if (isvalid === false) {             settimeout(this.setisvalid(isvalid), 2000);         } else {             this.setisvalid(isvalid)         }     }     getclassname() {         var classname = ''         var errorclass = ''          // generate error classes based on input validity.         if (this.state.isvalid) {             errorclass = ''         } else {             errorclass = 'error'         }          classname = 'number-input ' + errorclass         return classname     }     render() {         return (             <div>                 <input type="text" classname={this.getclassname()} value={this.state.value} onchange={this.handlechange.bind(this)} placeholder="enter number"/>                 <rawnumber isvalid={this.state.isvalid} value={this.state.value} />             </div>         )     } } 

you need fix following line of code:

if (isvalid === false) {     settimeout(this.setisvalid(isvalid), 2000); } 

what doing here, calling this.setisvalid instantly , passing settimeout result of it. state changed instantly.

what want do, want pass settimeout function itself, not result. it, want wrap this.setisvalid function wrapper, this:

if (isvalid === false) {     settimeout((function() {         this.setisvalid(isvalid);     }).bind(this), 2000); } 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -