Hey there! If you've played around with React before, you've probably run into situations where you needed to show or hide things on your page based on what users do or what's happening in your app.
Don't worry - In this post, I’ll break down React's Conditional Logic in a way that's super easy to understand. I'll walk you through the basics and show you how to use it in your projects.
We'll start with simple stuff and work our way up to some cool tricks, with plenty of real examples along the way.
With an if statement
In React, we often need to render markup conditionally. For instance, we might want to display a small green dot next to user names when they're online.
Here's the good news, we can use an if
statement! But we have to pull it up so that it's not in the middle of a React.createElement
call:
There's no rule that says that our JSX has to be part of the return
statement. We can absolutely assign chunks of JSX to a variable, anywhere within our component definition! In the code above, prefix
will either be assigned to a React element, or it won't be defined at all – This works because React ignores undefined values.
Undefined attributes
Consider the following code:
function Greeting() {
let someClass;
return (
<div className={someClass}>
Hello World
</div>
);
}
What do you expect the markup to look like?
The following HTML will be produced:
<div>
Hello World
</div>
In the code above, a variable named someClass
is created, but it isn't given a value. This means that it resolves to undefined
.
When React sees that an attribute is being set to undefined
, it omits that attribute entirely from the DOM node. Rather than give it an empty value like className=""
, it acts as though we haven't even tried to set a value.
This is true for some other falsy values as well, like null
and false
.
With &&
Here's the thing about using if
statements - they force us to write our logic separate from our markup. While this works fine, it can get messy and confusing, especially when you're working with bigger components. You might find yourself scrolling up and down trying to figure out what's actually being shown on the screen!
But don't worry! There's actually a neat trick to write conditional logic right inside your JSX using the &&
operator.
Here’s how we’d do it:
In JavaScript, &&
is a control flow operator. It works quite a bit like if/else, except it's an expression instead of a statement.
To help us understand what's actually happening here, let's take a look at the same logic, but expressed using if
/else
:
function User({ name, isOnline }) {
let prefix;
if (isOnline) {
prefix =<div className="online-green-dot"/>;
} else {
prefix = isOnline;
}
return (
<li className="user">
{prefix}
{name}
</li>
);
}
The &&
operator is said to be a “control flow” operator because, like if/else, it will always result in one of two paths being taken.
If the left-hand value (isOnline
) is falsy, the expression short-circuits, and evaluates to isOnline
, which resolves to false
. If that value is truthy, however, it evaluates to whatever's on the right-hand side of the operator (<div className="green-dot" />
).
Common gotcha: the number zero
Consider this situation:
function App() {
const shoppingList = ['avocado','banana','cinnamon'];
const numOfItems = shoppingList.length;
return (
<div>
{numOfItems && (
<ShoppingListitems={shoppingList}/>
)}
</div>
);
}
We have a component, ShoppingList
, and it only really makes sense to render that component if we have at least 1 item in our shopping list.
If you've been using JavaScript for a while, you might know that every number in JS is truthy except 0.
→→→ 0 is the only falsy number, just like how ''
is the only falsy string.
Therefore, it seems to make sense to do things this way. If numOfItems
has at least 1 item in it, it will be truthy, and we'll render the <ShoppingList>
element. If we have 0 items, we should skip it.
If we run this setup, we wind up with 0
being rendered!
Why is this happening? We need to keep two things in mind:
- The
&&
operator doesn't returntrue
orfalse
. It returns either the left-hand side or the right-hand side. So, when our list is empty, this expression evaluates to0
. - React will render any number you give it, even zero!
React will ignore most falsy values like false
or null
, but it won't ignore the number zero.
In fact, let's see how React handles all the different falsy values:
function App() {
return (
<ul>
<li>false: {false}</li>
<li>undefined: {undefined}</li>
<li>null: {null}</li>
<li>Empty string: {''}</li>
<li>Zero: {0}</li>
<li>NaN: {NaN}</li>
</ul>
);
}
export default App;
The console log 👀 will look like this:
false:
undefined:
null:
Empty string:
Zero: 0
NaN: NaN
Solution: Use boolean value with &&
Here's a handy tip to keep your app clean: when using the && operator, always make sure the thing on the left side gives you a true or false answer. This way, you won't get any unexpected zeros showing up in your app!
Let me show you what I mean - you can check if a number is bigger than zero:
function App() {
const shoppingList = ['avocado','banana','cinnamon'];
const numOfItems = shoppingList.length;
return (
<div>
{numOfItems > 0 && (
<ShoppingListitems={shoppingList}/>
)}
</div>
);
}
I really like this approach. We're being really specific with what the condition is: if we have 1 or more items in the shopping list, we should render the <ShoppingList>
element. The “greater than” operator (>
) will always produce a boolean value, either true
or false
.
We can also convert any non-boolean value to a boolean value with !!
:
function App() {
const shoppingList = ['avocado','banana','cinnamon'];
const numOfItems = shoppingList.length;
return (
<div>
{!!numOfItems && (
<ShoppingListitems={shoppingList}/>
)}
</div>
);
}
You can how see how this operator works here
With ternary
So the &&
operator is great when we want to show something based on a condition. But what happens when we intend to show one thing OR another thing depending on that condition?
Let's say we're making a dashboard for website admins. When someone's logged in, they should see all their cool admin stuff like charts and data. When they're not logged in, we would like to show them a friendly message asking them to log in first.
One way to do this is by using two &&
operators side by side, like this:
function App({ user }) {
const isLoggedIn = !!user;
return (
<>
{isLoggedIn &&<AdminDashboard/>}
{!isLoggedIn &&<p>Please login first</p>}
</>
);
}
This works, but it's a bit clunky. Fortunately, we can use the ternary operator to help us out.
Here's what it looks like:
function App({ user }) {
const isLoggedIn = !!user;
return (
<>
{ isLoggedIn ? <AdminDashboard/> : <p>Please login first</p> }
</>
);
}
It's particularly useful in a React context because it allows us to embed if/else logic within our JSX. Because the ternary operator is an operator instead of a statement, it can be used inside JavaScript expressions.
A ternary operator consists of three parts:
condition ? firstExpression : secondExpression
If condition
is truthy, the first expression will be the one that gets evaluated. If it's falsy, the second expression will be evaluated instead.
The
&&
operator works in much the same way:false && console.log('I will never run!');// Nothing is logged
When the evaluator sees that the left-hand value is falsy, it "short-circuits" and ignores everything that comes afterwards. In other words, it's safe to do something like this:
const networkRequest = isLoggedIn && fetch('/user/login-details');
The
fetch()
call will only execute if isLoggedIn
is true. So we don't have to worry about "wasted" network requests.Showing and hiding
In the examples we've seen so far, our strategy has been to selectively add or remove a chunk of markup to the page.
There is another way to solve this problem, however. Depending on your background, you might be much more familiar/comfortable with this method.
Instead of adding and removing whole HTML elements, we can toggle their visibility using CSS.
Here's what this looks like in React:
function User({ name, isOnline }) {
const style = isOnline ? undefined : { display:'none' };
return (
<li>
<div className="online-green-dot" style={style} />
{name}
</li>
);
}
If the user is online, style
will be undefined
, and will have no effect. The green dot will be shown.
If the user is offline, the green dot will have display: none
applied, effectively removing it from the UI.
So which approach is better - conditionally rendering elements with JavaScript operators or using CSS to show/hide them?
From a usability standpoint, both methods are equivalent. When you hide an element with
display: none
, it's effectively removed from the page - both visually and functionally. This includes keyboard navigation and screen-reader accessibility.In conclusion
This comprehensive guide explores three main approaches to React conditional rendering:
- Using the && operator for simple show/hide functionality, with important considerations for handling zero values
- Implementing ternary operators for elegant if/else conditional rendering
- Utilizing CSS display properties as an alternative approach to visibility control
Each method serves specific use cases, and choosing the right approach depends on your requirements. Understanding these patterns is crucial for building dynamic and maintainable React applications.
🔍. Similar posts
How to Handle Asynchronous Updates with useState in Your React App
30 Jan 2025
How to Effectively Use Event Handlers in React with Arguments
28 Jan 2025
The Simple Guide to React Range Utility for Effective Coding
26 Jan 2025