Conditional rendering in React - using the && operator
Arika O
Posted on April 20, 2020
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:
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:
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:
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:
Article No Longer Available
Article No Longer Available
For the complete code I wrote today, you can go here: https://codesandbox.io/s/conditional-rendering-the-operator-42jxi?file=/src/App.js
Posted on April 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.