Conditional Rendering in JSX

Conditional Rendering in JSX

Conditional Rendering in JSX

Conditional rendering is very similar to the conditional statements in all languages, simply the working principle of conditional statement depends upon the condition, if it is true, set of statements are executed, or else another set of statement gonna execute. In JSX, We can use three types of methods to achieve conditional rendering.

  • If statement
  • Ternary operator
  • Logical AND operator

Here we are assuming a simple example,

Pseudo code :

if age of the username is greater than 18 :
   elected to vote
else :
   Unable to vote

if statement

The simplest and most frequent method is using if statement,

var age  = 19
function ageCheck(){
if( age > 18)
      return age
}
<p>Age : {ageCheck()}</p>

Ternary Operator

Another method is by using ternary operator (? :), If the condition before ? becomes true, the statement after ? will get executed or else the statement after : will get executed.

var age  = 19
<p>{ age >18 ? age : undefined }</p>

This will print the age in p, if it is greater than 18.

Logical AND Operator

This is one of the new and efficient way to implement conditional statements in JSX. Consider the same example, We already know the working principal of AND operator

Input 1Input 2Output
000
010
100
111

Output will be true only if the two inputs are true. Now we understood the working logic of Logical AND(i.e) first statement && second statement (Second statement will get executed only if the first statement will get true).

var age = 19
{age > 18 && <p>Age : {age}</p>}

If the age > 18 is true (i.e)first statement, it will move on to the second statement and print the age value.

These are the three common practices to implement conditional statements in JSX.

Thank you for reading !! reach me @ Rathesh Prabakar