-1

I found this code for creating a function-based component in the React documentation :

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Bonjour !</h1>
      {unreadMessages.length > 0 &&
        <h2>
          Vous avez {unreadMessages.length} message(s) non-lu(s).
        </h2>
      }
    </div>
  );
}

Why is there no if keyword before the unreadMessages.length > 0 ?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
pheromix
  • 18,213
  • 29
  • 88
  • 158
  • 2
    You can't put `if` in JSX because all JSX inside `{}`s needs to be expressions. Otherwise, this is vanilla JS short-citcuiting boolean condition. If the left of the `&&` is false, JS never evaluates the right side and returns false immediately, rendering nothing, otherwise it returns the element on the right side. – ggorlen Jan 27 '21 at 06:24
  • Does this answer your question? [if-else statement inside jsx: ReactJS](https://stackoverflow.com/questions/44046037/if-else-statement-inside-jsx-reactjs) – Emile Bergeron Jan 27 '21 at 06:37

2 Answers2

1

In JSX markup, { indicates to start interpreting the following as a JavaScript expression (which may include JSX) rather than as unconditional JSX. The expression inside the {} then essentially gets interpolated into the outer JSX.

But if cannot exist where a JavaScript expression (that is, something that evaluates to a value) is required. For the same reason, the following is a SyntaxError:

const thisIsInvalid = if (true) 'yes';

because if does not evaluate to a value, and cannot be used in an expression context.

Transpiled, the code in your question looks something like:

React.createElement(
  "div",
  null,
  React.createElement("h1", null, "Bonjour !"),
  unreadMessages.length > 0 &&
    React.createElement(
      "h2",
      null,
      "Vous avez ",
      unreadMessages.length,
      " message(s) non-lu(s)."
    )
);

The second child expression uses && to either evaluate to false (if unreadMessages.lengthis 0), or to theReact.createElement`.

You can't use if in your JSX for the same reason that the following syntax doesn't make sense and isn't allowed:

React.createElement(
  "div",
  null,
  React.createElement("h1", null, "Bonjour !"),
  if (unreadMessages.length > 0) {
    // ...

Instead, you can only use constructs that are valid as expressions, such as chaining together different expressions with logical operators.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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

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.

More explanation to this over here

HexaCrop
  • 3,863
  • 2
  • 23
  • 50