1

I've been writing Coffeescript/CJSX and this is valid syntax:

<div>
   <input type={if @state.name == "Test" then "checkbox"}/>
</div>

How do I do the same for plain Javascript? There is no if...then clause and I don't think I can do inline if checks like I can in Coffee?

Jonathan Allen Grant
  • 3,408
  • 6
  • 30
  • 53
patrickhuang94
  • 2,085
  • 5
  • 36
  • 58

2 Answers2

2

You can also use logical operators:

<input type={(state.name == "Test" && "checkbox") || "text"}>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Short-Circuit_Evaluation

inostia
  • 7,777
  • 3
  • 30
  • 33
  • 3
    Sure, you _can_ do that, but why would you? This is also subtly different in behavior from `?:` and could lead to insidious bugs if you're not careful. – JLRishe Aug 24 '16 at 04:23
  • 1
    That's true. I mostly use it to render elements in JSX. I.e. `{state.isValid &&

    Valid!

    }`. But i think you're right in this case that the ternary is correct.
    – inostia Aug 24 '16 at 18:27
1

Taking the answer from How to write an inline IF statement in JavaScript?

You can use the syntax 10 < 11 ? do this : do that where the ? is the then and the : is the else.

Community
  • 1
  • 1
Jonathan Allen Grant
  • 3,408
  • 6
  • 30
  • 53