Table of Contents
What is Conditional Rendering?
While developing an application in React or any other JS library/ framework, it is a common use case to show or hide elements based on certain conditions. It can be a simple user interaction – say, we need to show a popup when a user clicks a certain button and hide it when (s)he clicks the cross icon. To quote another example, think authentication – we make a ‘log out’ button visible when (s)he is logged in and make ‘Login/Sign up’ form visible for the opposite situation. This process of executing logic or rendering UI elements basis certain conditions is called conditional rendering.
In this article, we’ll be discussing conditional rendering in ReactJS and looking at different ways to handle those cases. We cover below the most useful methods for conditional rendering in react:
- Ternary operation
- Inline IF with Logical && operator
- Switch case operator
- Conditional Rendering with enums
- Higher-Order Components
Let’s observe the example below.
Consider these two components:
We’ll create a LoggedStatus component that displays either of these components depending on whether a user is logged in or not. A different greeting is rendered depending on the value of isLoggedInprop.
condition ? “This is True” : “This is False”
When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”.
How can we use this in React JS?
Consider this use case – Show an “Update” button when an edit has been made, else, show the “Edit” button.
In the above example, when “edited” is true, we’ll show the “Update” button to the user. If “edited” is false, the “Edit” button is rendered.
Inline If with Logical && Operator
&& is a boolean operator, which essentially means “and”. For the condition to evaluate to true, both of the statements must be individually true.
Below is an interesting example. Let’s say we want to render a message saying “You have X tasks to do”. When there are no pending tasks, no message should be displayed.
Observe carefully – When the length of the array is 3 (which is > 0), we’ll print, “You have 3 Tasks to do.” If the length is 0, we print nothing.
Switch Case operator in React
Note carefully though that you always have to use default for the switch case operator since in React, a component always needs to return an element or null.
To make it cleaner, we can get the switch out of the render in a function and just call it passing the params we want. See the example below.
In a nutshell, the switch case operator helps us to have multiple conditional renderings. That’s great!
Hold on, but this may not be the best way to achieve multiple renderings. Conditional renderings with enums is much more neat and readable compared to the switch case operator. Let’s then see how we can have multiple conditional renderings with enums.
Conditional Rendering with enums
Let’s look at an example. We want to create three different components Foo, Bar and Default. We want to show these components based on a certain state.
We’ll now be creating an object that can be used as an enum.
Let’s now create a function that will take state as a parameter and return components based on “state”. The “EnumState” function below is quite self-explanatory.
The state property key above helps us to retrieve the value from the object. You can see that it is much more readable compared to the switch case operator.
Let’s create an Enum component, which will pass the values of “state” to the function “EnumState”.
That’s it! We have conditional rendering implemented smoothly with enums. For the full example, check out this Codepen link.
As we saw, the enum approach is more readable in comparison to the switch case statement. Objects as enum open up a plethora of options to have multiple conditional renderings.
Higher Order Components
Higher order components or HOCs are often considered a difficult pattern to grasp in ReactJS. HOCs can be used for multiple use cases, however in this article, we’ll be picking up HOC for conditional rendering.
HOCs are a perfect match for conditional rendering in React and can have several use cases. One of them can be to alter the look of a component. To make it more specific, it can be used to conditionally render the component itself.
Let’s now take a look at a HOC that either shows a loading indicator or the desired component.
In the above example, the List component can focus on rendering the list. It doesn’t have to bother about a loading state. Ultimately, we could add more HOCs to shield away multiple conditional rendering edge cases.
In summary, we saw multiple ways to achieve conditional rendering in React. Each approach has its own advantages and some, like the enum approach can help you achieve more readable code than others. Simplicity, though, is also an important consideration when using any of these approaches – all your use case may need is just the if operator. In effect, pick the approach that best fits your use case at hand and hope we simplified your decision making a bit through this article 🙂