Kyle Woolley
Kyle Woolley

Reputation: 813

Explanation on why ternary statement is not working like expected in React

Assuming this.health() //returns 'default', why does

<div className="guage">

    // Why do these work as intended

    <div className={"guage-segment default " + (this.health() === 'default' ? 'active' : '')}>Default</div>
    <div className={"guage-segment danger " + (this.health() === 'danger' ? 'active' : '')}>Danger</div>

   // When I feel like this is the proper ternary syntax

    <div className={"guage-segment ok " + (this.health() === "ok") ? "active" : ""}>Ok</div>
    <div className={"guage-segment good " + (this.health() === "good") ? "active" : ""}>Good</div>

</div>

The first two guage-segement add the active class only when the condition is true, however the next 2 return active no matter what. I thought ternary syntax was (condition) ? true : false but it seems that (condition ? true : false) is what is working. Any explanation would be great.

Upvotes: 1

Views: 181

Answers (1)

iceveda06
iceveda06

Reputation: 619

() works because of Order of Operation. () is the highest, if you remove () then addition will go first from left to right.

Here is MDN list of precedence from highest to lowest:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

Upvotes: 4

Related Questions