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 the
React.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.