Correct way to handle conditional styling in React

前端 未结 9 1246
逝去的感伤
逝去的感伤 2020-11-27 04:25

I\'m doing some React right now and I was wondering if there is a \"correct\" way to do conditional styling. In the tutorial they use

style={{
  textDecorati         


        
9条回答
  •  眼角桃花
    2020-11-27 04:39

    instead of this:

    style={{
      textDecoration: completed ? 'line-through' : 'none'
    }}
    

    you could try the following using short circuiting:

    style={{
      textDecoration: completed && 'line-through'
    }}
    

    https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb

    key bit of information from the link:

    Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.

    It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.

    The other solutions might be more best practice, but thought it would be worth sharing.

提交回复
热议问题