0

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 |           }
2
  • 1
    Please show the code along with the error message. Commented Sep 27, 2019 at 15:44
  • You can't use statements inside JSX, only expressions. It's quite common to use ternary operator in JSX Commented Sep 27, 2019 at 15:51

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.