Reputation: 10614
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
as they are not-checked then on each event I'm trying to change there value respectively (ie if false the true & vice versa).
On following this SO post I tried this:
(event.target.value=='BILLDED') && billed=(!billed)
By doing this I get:
Syntax error: Invalid left-hand side in assignment expression
Then I tried this:
(event.target.value=='BILLDED') ? (billed=(!billed)) : null
However, it gives me BILLED:true
on every onChange
(when clicked on BILLED checkbox
)
This is code for checkbox inside render method:
render() {
return (
<div>
<form onChange={this.checkBoxOnChange}>
<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){
var billed=false;
var pending=false;
// (event.target.value=='BILLDED') ? (billed=(!billed)) : null;
(event.target.value=='BILLDED') && billed=(!billed)
// (event.target.value=='PENDING') ? pending=(!pending) : null;
console.log("BILLDED:"+billed+" PENDING:"+pending);
}
Upvotes: 2
Views: 4846
Reputation: 28654
However, it gives me BILLED:true on every onChange (when clicked on BILLED checkbox)
Is this not because you use a local variable as below
var billed=false;
which always starts as false
?
Upvotes: 1
Reputation: 664425
What's wrong with the code?
You initialise the billed
variable inside your event handler to false
, that's why you always get true
instead of toggling a state.
Can I not use inline statement for this scenario?
You can, you just have to put the parenthesis in the right place:
(event.target.value == 'BILLDED') && (billed = !billed);
// ^
Is there any better, more concise approach?
Use a normal if
statement. It's both shorter and more readable:
if (event.target.value == 'BILLDED') billed = !billed;
Upvotes: 4