Search code examples
reactjsecmascript-6inlineternary-operator

Ternary Operator (Inline If without Else)


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);
  }
  • What's wrong with the code?
  • Can I not use inline statement for this scenario?
  • Is there any better, more concise approach?

Solution

  • 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;