⚠️ This lesson is retired and might contain outdated information.

Render React Components conditionally with short circuits

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 2 years ago

In this lesson you will learn yet another way of using short circuit operator in JavaScript on the basis of React conditional rendering example

Dimitri Ivashchuk: [00:00] Using short-circuit operators. JavaScript is using them in React. Here we see that we are in React application. We have a simple button that has setCondition in onClick handler. This setCondition just changes the state of condition Boolean from true to false. It just toggles it from false to true and vice-versa.

[00:25] When we click the button, the smiley appears, which means that condition is true. Currently, we are rendering it with ternary operator, which just renders now if condition is false or falsy. We can refactor it to be using the short-circuit.

[00:45] Let's just copy this span here. Let's delete this code. We can make it almost a one-liner, so condition &&, and then we have a span rendering if it's there.

[01:02] We could still see that it's working fine, and that's because, if the condition is false, it will just be cut down and not render anything. It won't reach this part of the expression. If the condition is true and when we have the toggle on true value, it will show the span element respectively.