Why can I use a ternary operator inside a JSX expression but not an if statement?
Answer
We can use a ternary operator, also known as a conditional operator, inside a JSX expression because it will always evaluate to a value, where as an if/else/else if statement is not only not an expression (it’s a statement and will execute a statement based on the value of an expression), but will also not evaluate to a value.
In other words, we cannot use a statement where a value (or expression) is expected and for this reason, we cannot use statements, including the conditional if/else/else if statements, inside a JSX expression.
If we really want to use an if statement inside a JSX expression, I think there is a way that we rewrite it as a function which always returns a value, and call it immediately. I tried the following code and this worked too:
I just want to confirm whether i am getting your code the right way !!
As far as I can assess you have made an arrow head function and used () to make it a function call !
if-else statements don’t work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
This means that if statements don’t fit in. Take this example:
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>
// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
That’s not valid JS. You probably want to make use of a ternary expression:
I can try to answer your question.
The ternary operator is already basic JS and it does not need any transformation.
So the JSX element <div id={condition ? 'msg': null }>Hello World!</div> would be translated to: