What is Conditional Rendering?
Many websites want users to create an account that requires you to sign in when using the site. Any social media, blogging platform, or e-commerce site will often even require you to have that account.
When you go to sign in, you will often click on a button that says something like 'Login' but what happens to that button after you're logged in? It usually changes to 'Logout' until you sign out, after which it says 'Login' again. This is a common example of conditional rendering.
Conditional rendering is when you set conditions in your code that impacts what gets displayed for a user. Some examples could be single html elements on the page (like a login/logout button) or even entire React components (like navigating to a Contact Us form for customers). Some defined condition must be met for a certain kind of display to present for the user.
How to Implement Conditional Rendering in Your React App
While there are several ways to implement conditional rendering, today I'm only going to talk through my go-to method: ternary operators. They rely on requiring only two possible displays, but other methods could give more than two possible paths; switch allows for three or more conditions.
We'll talk through a like button, which is a common use case, and use that as the base of our example.
Ternary Operator - A Like Button
As a reminder, a ternary operator takes three arguments. The first will return a Boolean value of either true or false. If true, the ternary will implicitly return the second argument; if false, it will return the third.
In the code below, we have some Boolean value 'liked' associated with a certain post in some social media platform for a particular user. If they haven't liked it yet, the button will display "Like"; if they have, the button will display "Liked". While not included here, typically there would also be click events located in the button tag to allow the user to toggle between displaying "Like" and "Liked" in the browser.
// Example #1
<button>{ liked ? "Liked" : "Like" }</button>
// Example #2
{ liked ? <button>Liked</button> : <button>Like</button> }
Either example above will produce the same display.
In example #1, we have a single ternary located inside the button tag. When the element itself doesn't change and either display will use the same click events, this can be a clean and efficient way to structure the code.
In example #2, you are returning two separate elements. While the example we're working with doesn't appear to require writing out that much code, it can be very useful if you are choosing between two different html elements or whether or not to be able to hide/show that element on the page.
Toggle Between Showing/Hiding Elements
Say we are scrolling through a catalog of images with any details hidden on load, but a user can click a "Show Details" button below any image to display them. In React, we could create a separate component for those details.
This might require code that looks something closer to the following (albeit with some details like click events and state missing - more on that below):
import ItemDetails from './ItemDetails.js'
function ItemContainer({item}) {
return (
<div>
<img src={item.image} alt={item.description}></img>
<button>{ showDetails ? "Hide Details" : "Show Details" }</button>
{ showDetails ? <ItemDetails item={item} /> : null }
</div>
)
}
An image displays along with a button that allows you to show/hide details. When showDetails is false, nothing will display. When it is true, you'll display the ItemDetails component along with the image right there on the page.
When to Leverage State
The previous example is a great segue into how state can be leveraged in conditional rendering. Showing and hiding details does not rely on static data, but rather on the behavior of the user in that particular instance.
Using state is a very easy way to accomplish what we need. Building upon our example, we can do the following:
import ItemDetails from './ItemDetails.js'
import {useState} from 'react' // don't forget to import!
function ItemContainer({item}) {
// set state you'll use in click event
const [showDetails, setShowDetails] = useState(false)
//define your click event function
function handleClick() {
setShowDetails(!setShowDetails) // toggle between true/false on click
}
return (
<div>
<img src={item.image} alt={item.description}></img>
<button onClick={handleClick}>{ showDetails ? "Hide Details" : "Show Details" }</button>
{ showDetails ? <ItemDetails item={item} /> : null }
</div>
)
}
Wrapping Up
This post is only a brief introduction to conditional rendering and how we use ternary operators to implement them. There are many other methods to explore that may be more useful in different contexts. We also touched on how state can be a useful tool in conditional rendering.
If you found this tutorial helpful, like and follow for more posts to come!
Top comments (5)
Quick little variation that I like when you render
null
if the condition isfalse
:{ showDetails ? <ItemDetails item={item} /> : null }
This can be replaced by
{ showDetails && <ItemDetails item={item} /> }
This might be a little confusion at first glance, but it does tell you right at the start that this is simply an on/off rendering. You know you don't have to scroll down to see what is rendered when the condition is
false
.I hadn't seen that syntax before - thanks for sharing!
another short way of rendering is:
{ showDetails && }
Cool article, learned some new stuff.