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

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -