reactjs - Updating State dynamically with React using Checkboxes -


i have checkbox called animal. when checkbox selected, this.state.animal set true , animal-filter div shown.

<input type="checkbox" checked={this.state.animal} onchange={this.checkanimal} /> animals  {this.state.animal ?  <div classname="animal-filter"> <div classname="checkbox">   <p><input type="checkbox" checked={this.state.dog} onchange={this.checkdog} /> aa </p>     </div>     <div classname="checkbox">   <p><input type="checkbox" checked={this.state.cat} onchange={this.checkcat} /> a</p>     </div>     <div classname="checkbox">   <p><input type="checkbox" checked={this.state.fish} onchange={this.checkfish} /> b</p>     </div> </div> : null} 

my problem want these checkboxes of cat, dog , fish set true instantly once animal state set true. know react setstate not update state automatically how make such that, when animal checkbox "checked" other checkboxes set true vice versa?

my code updating state:

checkanimal(){   this.setstate({animal: !this.state.animal});       if (this.state.animal !=true){      this.setstate({       cat:false,       dog:false,       fish:false,    });    }else{      this.setstate({        cat:true,        dog:true,       fish:true,    });         } } 

thecheckanimal method can drastically simplified to

checkanimal() {   this.setstate({     animal: !this.state.animal,     cat: !this.state.animal,     dog: !this.state.animal,     fish: !this.state.animal,   });    } 

this guarantee when animal checkbox checked, cat, dog , fish checkboxes stay in sync it's state.

also, there references this.state.animal capital a in jsx incompatible this.state.animal accessed in checkanimal method.

e.g. {this.state.animal ? watch out.

consider using javascript code linter eslint catch errors that.


Comments