Skip to Content
Learn
Advanced JSX
JSX Conditionals: &&

We’re going to cover one final way of writing conditionals in React: the && operator.

Like the ternary operator, && is not React-specific, but it shows up in React surprisingly often.

In the last two lessons, you wrote statements that would sometimes render a kitty and other times render a doggy. && would not have been the best choice for those lessons.

&& works best in conditionals that will sometimes do an action, but other times do nothing at all.

Here’s an example:

const tasty = ( <ul> <li>Applesauce</li> { !baby && <li>Pizza</li> } { age > 15 && <li>Brussels Sprouts</li> } { age > 20 && <li>Oysters</li> } { age > 25 && <li>Grappa</li> } </ul> );

If the expression on the left of the && evaluates as true, then the JSX on the right of the && will be rendered. If the first expression is false, however, then the JSX to the right of the && will be ignored and not rendered.

Instructions

1.

You’ve been building a React website all about your favorite foods!

You’re excited to share your website with your friends, and yet at the same time, you fear the cruel, icy harshness of their judgment.

On line 13, use the && operator to make it so that this expression:

<li>Nacho Cheez Straight Out The Jar</li>

…will only appear if !judgmental. Feel free to use the example code as a guide.

Once you click Run, then every time that you refresh the browser, there will be a 50% chance that judgmental will be true. Refresh until you see both versions of your list.

Folder Icon

Take this course for free

Already have an account?