Short Circuit Evaluation with React
Mark Harless
Posted on April 26, 2020
I've been playing with React for several months now. I love it. Reusable components makes front end developing so much easier and enjoyable. Rendering these components using conditional rendering is something I enjoy coding, and I'm not sure why. It's not hard, it's sometimes not easy but I like it regardless. In this blog post, I'm going to show you how to render a component using the "logical &&
" method.
Let's consider this code:
import React, { useState } from 'react'
import Welcome from '../components/Welcome'
function About() {
const [showWelcome, setShowWelcome] = useState(false)
return (
<div>
{showWelcome ? <Welcome /> : null}
</div>
)
}
export default App
The code above is a crude illustration of a homepage. If a user is logged in, we want to greet them by rendering <Welcome />
. If the user isn't logged in, we don't want to show anything.
So, in between the div
s we have a ternary operator. A ternary operator is basically a shorthand for an if... else
statement.
if
showWelcome
is true
then render <Welcome />
or else
render nothing.
But there's a simpler way to do this using "logical &&
". Using the same logic, we can code the following:
{showWelcome && <Welcome />}
Wait a minute 🧐.
At first, it may not make sense. It didn't for me. Let's think about. The &&
logical operator means that both conditions on either side of it have to be met in order for it to be true
. Right now, as the code stands, showWelcome
is false
because that's what it's initially set at by useState
. So nothing, or null
, would be rendered. If it were set to true
, however, both conditions would be successfully met and then render <Welcome />
.
I thought this was a clever way of rendering a component if there wasn't a need for an else
statement. If you do need to render one component or another, it's best to use a normal ternary operator as shown in the first code block!
Posted on April 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.