if-else statements inside JSX does not work in ReactJS

Inside JSX of ReactJS we always feel the need of conditional rendering. Inside JSX we can only write expressions not the statements. This means directly we can not put any statement (if-else/switch/for) inside JSX code.

What’s in the doc:

Clarification from the doc:

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

What JSX becomes after compilation

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

Example of why statements do not work?

<div id={condition ? 'msg' : null}>Hello World!</div>

becomes following JavaScript code: 

React.createElement("div", {
  id: "msg"
}, "Hello World!");
<div id={if (condition) { 'msg' }}>Hello World!</div>

becomes following JavaScript code: 

React.createElement("div", {
  id: "if (condition) { 'msg' }"
}, "Hello World!");
// Invalid JavaScript

But expression works nicely. See the example below:

<div id={condition ? 'msg' : null}>Hello World!</div>

becomes following JavaScript code: 

React.createElement("div", {
  id: "{condition ? 'msg' : null}"
}, "Hello World!");
// valid JavaScript
Share