This is a follow up question of this question. I'm trying to log
the value of two check boxes in terms of true or false.
I have two checkbox
in a <form>
. The <form>
have an onChange={this.checkBoxOnChange}
assigned to it which fires up checkBoxOnChange(event){..}
function on every change in the form. I am trying to map_(Log)_ the status (ie whether they are checked or not). So, I've initially taken there value as false
in this.state()
inside constructor()
as they are not-checked(initially) then on each event I'm trying to change there value respectively (ie if false the true & vice versa).
But, when I'm trying to log their output they are printing in wrong order. Checking on checkbox is even changing value of another checkbox.
This is code for checkbox inside render method:
render() {
return (
<div>
<form onChange={this.checkBoxOnChange.bind(this)}>
<input type="checkbox" name="invoicestatus" value="BILLDED" />BILLDED<br />
<input type="checkbox" name="invoicestatus" value="PENDING" />PENDING<br />
</form>
<ListData data={this.state.data}/>
</div>
);
}
};
This is the checkBoxOnChange()
function within that same class (Component):
checkBoxOnChange(event){
console.log("BILLDED"+this.state.billed+"PENDING"+this.state.pending);
(event.target.value=='BILLDED') && (this.setState({billed:(!this.state.billed)}));
(event.target.value=='PENDING') ? (this.setState({pending:(!this.state.pending)})) : null;
console.log("BILLED"+this.state.billed+" PENDING"+this.state.pending);
}
Initial value is being set as:
constructor(props){
super(props);
this.state = {
data:[],
billed:false,
pending:false
}
}
- Why I am getting wrong values?
- How do I make it work in proper order?
This question is different from this SO post on following grounds:
- Because both the solution to this question mention about Uncontrolled Components vs Controlled Components
- Annnd there's also and awesome setState()
feature of React prevState by which I was (& would be) unaware of, if I'd (or someone else) follows above mentioned post.