React Conditional Rendering with the Ternary Operator & AND Operator

JSX only allows you to use JavaScript expressions within curly braces. It does not allow you to enclose JavaScript statements.

So if you wanted to use a condition to decide which content to render on the screen, you COULD NOT use a statement like this:

return <div>{
   if (isLoggedIn === true){
      return <h1>My Favorite Foods</h1>
   } else {
      return <p>My Least Favorite Foods</p>
   }
}</div>;

Instead, you would have to use a ternary operator. This is how ternary operators work:

condition ? do if true : do if false
foodAtHome === true ? makeFood() : buyFood()

So this is how you would accomplish the task from above:

return <div>{
   isLoggedIn === true ? <h1>My Favorite Foods</h1> : <p> My Least Favorite Foods</p>
}</div>;

Another way you can incorporate logic into your JSX objects is with the AND operator. The AND operator in React checks if the first condition is true or false. If true, it looks to see if the expression is also true then displays the expression. If the statement is false, it will not even look at the expression.

condition && expression
true && expression
false && -expression-

Here’s an example of the AND operator:

return <div>{
   currentTime > 12 && <h1>It's not the morning</h1>
}</div>;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s