Cover image for Conditional rendering in React - using the && operator

Conditional rendering in React - using the && operator

ari_o profile image Arika O ・2 min read

As promised, I'm going to continue writing about conditional rendering in React and the most popular ways to achieve this behavior. Today we talk about rendering using the && operator. If it looks familiar that's because it is. We know it from Vanilla Javascript and it's called the and operator.

Let's say we want to display a component or no component (null), based on a condition. We could of course do that using a simple if statement. Like in the code bellow:

Alt Text

The problem with this is that we can't inline the condition in our JSX. To fix this, we could use the ternary operator and write something like:

Alt Text

But what if we want to skip the null rendering part all together? This is where && comes in handy. We can re-write the code like so:

Alt Text

On line 14, we say {condition && <Condition/>}, which means that the component will be rendered if what's before the && is true and it won't if what's before the && is false. This is called short-circuit-evaluation and it works like so: if the value on the left is true, it returns the value on the right. If the value on the left is false, it ignores the value on the right.

By now, you already learned about three ways to achieve conditional rendering in React: if/ else statements, the ternary operator and the && operator. If you would like to read the two previous articles on the subject, you can check the links bellow:

For the complete code I wrote today, you can go here: https://codesandbox.io/s/conditional-rendering-the-operator-42jxi?file=/src/App.js


Editor guide