Conditional Rendering in React

It might have happened or will surely happen with you that, you’d want to render the whole of the React component or a part of it based on some conditions according to the state of your component. That’s where conditional rendering will save you. In simple terms, conditional rendering is a way in which we can render the whole of our component or a part of it based on some condition. This almost works the same way as conditions work in JavaScript, and we can use conditional rendering in our React application in 4 ways:-

  1. if/else conditions

Let’s discuss each of those ways in detail:-

If/Else Conditional Rendering

The if-else in React works similar to how they were in JavaScript. The way we can make use of them to conditionally render our component is:

This method or approach deviates from the DRY (don’t repeat yourself) approach because the part that remains unaffected of the condition has to be repeated for both the if block & the else block. You might now think why not place the if-else within the JSX. Your thought is good but it is not possible as JSX is a syntactical sugar for function calls & object construction and because of that we cannot use if-else blocks within it.

Element Variables

In this approach, we use a JavaScript variable to store that particular element which depends upon the condition of our component. The way this approach is implemented is:

The main advantage of this approach is that it follows the DRY principle and we can render a particular part of a component-based on a specific condition without repeating the unaffected part again and again.

Ternary Conditional Operators

This is the most widely used approach when dealing with conditional rendering. This approach uses Ternary Conditional Operators (? :) to render the element based on a specific condition. This approach is implemented as shown:

As you might have noticed that unlike the if-else blocks the ternary operators can be used within the JSX, this is the main benefit of using this approach of conditional rendering and also the most widely used.

Short Circuit Operator

This approach is an extension to the 3rd approach using Ternary Operators. It is used when we want to render an element on the screen only if the condition is true, else we do not want to render anything. This approach uses && operator and can be implemented in the following way:

What happens in this approach is that first the left side of the ‘&&’ operator is evaluated and if the condition on the left is true the right side is returned, but if the left side is false nothing is returned.

This was all about Conditional Rendering in React, what it is and how to implement it. Hope you like it…



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store