In this blog post, we’ll talk about conditional rendering, perhaps the most important dynamic feature in React.
In simple words, conditional rendering is the feature where certain elements or components are rendered based on a condition. Usually based on current Boolean state value. If the Boolean is true, then render the component, and vice versa. In practice, there’s often a toggle or other user inputs that flips the Boolean value, so users can control whether or not the component is rendered. But let’s save that for later.
Most often, you need conditional rendering when dealing with data received from external source, or to toggle between full mode vs collapsed mode. This feature also comes in handy when dealing with authorization. It is also useful with forms, as you might want to display a feedback message only if there are errors.
So, without further ado, let’s explore how to implement conditional rendering in React. To follow along, you need to understand basics of JavaScript, React, and JSX. We are not going to explain simple things like how you need curly braces to embed dynamic JavaScript expressions inside JSX. It even allows you to set onClick on link, as shown in this guide.
IF/ELSE statement
We rarely get to use if/else in React, but it is a perfect choice to implement a conditional rendering feature.
As you probably already know, the return statement contains the JSX code that describes the component layout. JSX allows you to embed dynamic expressions, but you can not implement an if/else statement because it takes up multiple lines of code.
Instead, you need to use the if/else in the body of function component itself to return one component or another, depending on a condition. Remember that functional component itself, as well as everything else outside of return statement is a normal JavaScript code so you’re free to use any feature you’d like. In case of class components, use if/else in the render() function to specify the JSX layout of the return statement.
It will probably easier to understand by looking at an example:
function Button() {
const [isLoggedIn, setIsLoggedIn) = useState(false)
if (isLoggedIn) {
return <button>Log Out</button>
}
else {
return <button>Log In</button>
}
}
In this example, users will only see the ‘Log Out’ button if they’re currently logged in. And vice versa, they’ll see ‘Log In’ button if they are currently logged out. This is great for your app’s UX.
This method is best used when you have a small part of the page that needs to be conditionally rendered. For example, an authentication button. It’s best to encapsulate this logic in a small component like in this example, and then invoke the component and pass it a Boolean value. The child component should take care of the rest and have a small bit of logic that decides whether or not to render the element / component.
The switch statement
Switch statement is another conditional operator in JavaScript. It allows you to specify many more cases, and it may be useful if your condition for rendering a particular component involves comparing state value to a number, or measuring its length, or any of the non-boolean use cases.
As you know, switch, like if, accepts one argument. Then you write a series of case statements to set conditions to argument and compare it to numbers or any other use-case.
For example, let’s imagine you have a number state variable. If it Is below 10, you want to display warning text. If it’s between 10-20, display yellow text, and display green text in the rest of scenarios. That code would look something like this:
const someComponent() {
let [count, setCount] = useState(0)
switch (count) {
case count < 10:
return <p className=”redText”>Some warning text</p>
case count > 10 && count < 20:
return <p className=”yellowText”>Some warning text</p>
case count >= 20:
return <p className=”greenText”>Some warning text</p>
}
}
This is a very simple example where we handle three scenarios and render paragraph elements with different class values. We could render three entirely different components, that’s entirely up to your imagination.
When creating <label> elements, it’s important to remember that we use htmlfor in React, not ‘for’ attribute we use in HTML.
Ternary operators
Most React developers have probably used ternary operators to implement dynamic features inside JSX. Conditional rendering is no exception, as ternary operator allows you to conditionally invoke a certain component. Syntax is fairly simple, so this method could even be considered the easiest of all.
The main difference between a ternary operator and all other methods here is that you can embed a ternary operator directly within the JSX. So it may be the best used for simple use-cases, or when you need to conditionally render an element once and never again.
Ternary operator, however, does not allow you to embed much logic inside it like if/else and switch statements do. Technically you can have series of ternary operators to check multiple conditions, but the code becomes too complicated and difficult to follow.
Logical && Operator
Utilizing logical operators is probably the shortest way to conditionally render an element or a component. All you need is to understand how logical operators work (especially the AND && logical operator). You can even use OR || to chain more conditions and set up a complex condition.
Note that if you use AND logical operator, you’re still going to need to wrap it with curly braces inside JSX.
Despite its advantages in conciseness, using logical operators is not the most readable way to conditionally render components. But if you are confident that your teammates will understand what the logical operator does, then there’s no reason to not utilize it.
Summary
In this article we explored multiple ways to conditionally render components in React. This is an important aspect of building interactive web applications, where you want to conditionally show (or hide) certain parts of your UI.