DEV Community

Anojan Thevarasa
Anojan Thevarasa

Posted on

Different approaches to Conditional Rendering in React.js and when to use which!

Conditional Rendering

Conditional rendering in React.js is all about using the conditional operators of Javascript to dynamically render something out to the ReactDOM if and only when a specific condition is met. The 2 main types of conditional operators used in React rendering are:

  1. && (the AND) operator
  2. Ternary Operator

1. && (the AND) operator

The && operator checks for truthy or flasy (boolean) nature of an expression which can be taken advantage of for whether to render the given element or not. In other words, && operator can be used to determine to render something or not to render.
The syntax for the same would be:

condition && expressionToRender

For example, in order to render out a message when the number of messages meet a specific condition, it can be achieved as follows:

notifications.length > 0 && 
<h1>You have {notifications.length} notifications!</h1>
Enter fullscreen mode Exit fullscreen mode

2. Ternary Operator

A ternary operator makes use of the truthy and falsy conditions existing in Javascript universe. The ternary operator can be substituted in place of the verbose "if else" and "switch" statements, if the options are just two. The syntax for a Ternary operator is:
condition ? expressionIfTrue : expressionIfFalse

If the condition is true, the first expression after '?' gets executed; and if it is false, the second expression after ':' is executed. So in simple terms, the ternary operator can be used to render one of the given 2 expressions.

For example, in the same situation as above, to render out either of 2 different messages based on the length of notifications:

 notifications.length === 0 ?
                <h1>You're all caught up!</h1> :
                <h1>You have {notifications.length} unread  
               notifications</h1>
Enter fullscreen mode Exit fullscreen mode

In the above example, the message "You're all caught up!" (after "?") will be rendered out (displayed) if the notifications (stored in array) has 0 or no notification, which is checked using array.length method (before "?"). And if the notifications are 1 or more, the message in second h1 element (after ":") will be displayed (along with number of notifications derived with same array.method )

If Else and Switch statements

Though ternary operator can be used for more than 3 expressions as well, it's best practice to use if else or switch statements if the options are more than 2, to avoid complexity.

Top comments (0)