⚠️ 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 4 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.

Max Vyz
Max Vyz
~ 4 years ago

Hey, useful tip, but it's also good to mention that not all falsy values are working that way in this "short circuit" notation.

For example if you have some value of type number and you use that notation to decide whether to render the element or not, you might see 0 being rendered when the condition is falsy

Dimitri Ivashchuk
Dimitri Ivashchukinstructor
~ 4 years ago

Totally valid point! Forgot to mention this caveat, thanks for pointing out👍🏼 Nullish coalescence operator will be even easier and more predictable to use when it hits support for all of the browsers.

Markdown supported.
Become a member to join the discussionEnroll Today