With an If Statement
With the curly brackets, we can add JavaScript expressions within our JSX. Unfortunately, though, we can't add JavaScript statements.
As a result, this sort of thing is illegal:
function Friend({ name, isOnline }) { return ( <li className="friend"> {if (isOnline) { <div className="green-dot" /> }}
{name} </li> );}
Why doesn't this work? Well, let's consider how this would compile down to JavaScript:
function Friend({ name, isOnline }) { return React.createElement( 'li', { className: 'friend' }, if (isOnline) { React.createElement('div', { className: 'green-dot' }); }, name );}
The problem is that we can't put an if
statement in the middle of a function call like this — to look at a simpler example, it would be equivalent to trying to do this:
console.log( if (isLoggedIn) { "Logged in!" } else { "Not logged in" })
(For a refresher on the difference between expressions and statements in JavaScript, check out the primer lesson on “Statements vs. Expressions” 👀.)
Here's the good news, though: we can still use an if
statement! But we have to pull it up so that it's not in the middle of a React.createElement
call:
Code Playground
There's no rule that says that our JSX has to be part of the return
statement. We can absolutely assign chunks of JSX to a variable, anywhere within our component definition!
The JSX compiles to this:
function Friend({ name, isOnline }) { let prefix;
if (isOnline) { prefix = React.createElement( 'div', { className: 'green-dot' } ); }
return React.createElement( 'li', { className: 'friend' }, prefix, name );}
In the code above, prefix
will either be assigned to a React element, or it won't be defined at all. This works because React ignores undefined values.