KennyLogin
KennyLogin

Reputation: 19

'if () {} else {}' statement in React JSX?

I am simply trying to use an if/else statement in React in some JSX, but I get a "Parsing error: Unexpected token". The example ternary statement seems to work fine. Can you not use if/else statements in JSX?

  ./src/App.js
  Line 288:  Parsing error: Unexpected token

  286 |                   { this.getInvitesForEvent(dat.id, 
  this.invitesForEventData) }
  287 |                   { true === 1 ? 'empty set' : 'has results' }
> 288 |                   { if (true) { true } else { false } }
  |                         ^
  289 |                 </div>
  290 |               ))
  291 |           }

Upvotes: 0

Views: 1327

Answers (2)

Raphael Morgan
Raphael Morgan

Reputation: 210

to use if/else in jsx, you can do {condition ? results : results if condition isn't met} for example if you wanted to render the home page if someone was logged in but the login page if they weren't, you would do:

{ loggedIn ? <Home /> : <Login /> }

the "condition/variable ?" acts as a "if condition/variable" and the ":" acts as an else.

Upvotes: 0

Nicholas Tower
Nicholas Tower

Reputation: 85032

You can't do that inside the jsx, because only expressions can be put in jsx, not statements. If a ternary expression is inconvenient or illegible, you could consider doing an if statement outside the jsx

let val;
if (/*whatever*/) {
  val = true;
else {
  val = false;
}

return (
  <div>
    {val}
  </div>
)

As for why there's this limitation, it might help to remember what the jsx gets transpiled into. Doing <div>Hello</div> turns into React.createElement("div", null, "Hello");, and doing <div>{true ? 'true' : 'false'}</div> turns into React.createElement("div", null, true ? 'true' : 'false');

So what would <div>{if (true) { 'true' } else { 'false ' }}</div> transpile into? Something like React.createElement("div", null, if (true) { 'true' } else { 'false ' });, but it's illegal to put an if statement in the middle of that code. So it's also illegal to put it in the middle of the jsx.

Upvotes: 3

Related Questions