Conditional Rendering in React

Conditional Rendering in React

Conditional Rendering in React 1920 1440 Shuvo Habib

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:

  • if/else
  • Ternary operation
  • Inline IF with Logical && operator
  • Switch case operator
  • Conditional Rendering with enums
  • Higher-Order Components

React Conditional Rendering

if/else

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, and let React update the UI to match them. We use an if with our condition and return the element to be rendered.

Let’s observe the example below.

Consider these two components:

LoggedInUser Component:

LoggedOutUser Component:

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.

Ternary operation

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

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

Interestingly, we can write switch case inline just like normal Javascript for conditional rendering in React. However, you would need a self-invoking JavaScript function. Take a look at the implementation below.

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

In JavaScript, an object can be used as an enum when it is used as a map of key-value pairs.

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.

Conclusion

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 🙂

Shuvo Habib

Storyteller about JavaScript, new Frontend dev technologies, and A/B testing