React Conditional Rendering with Ternary Operator & AND Operator

Easy explanation

ยท

2 min read

React Conditional Rendering with Ternary Operator & AND Operator

Let's understand conditional rendering in React

Since you know that we can not use statements(example: loops, switch, if else statements) direct in our JSX but we want to render something based on a condition so here comes Ternary & AND Operator

Conditional (ternary) operator -

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is true followed by a colon (:), and finally the expression to execute if the condition is false. This operator is frequently used as an alternative to an if...else statement.

Syntax

CONDITION   ?   DO  IF  TRUE   :   DO  IF  FALSE

Let's understand by a simple example:

Example 1

function getMoney(condition) {
  return (condition ? '$5.00' : '$10.00');
}

console.log(getMoney(true));
// expected output: "$5.00"

console.log(getMonry(false));
// expected output: "$10.00"

console.log(getMoney(null));
// expected output: "$10.00"

Example 2

var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
console.log(beverage); // "Beer"

In example 2 you can clearly see that when age >= 21 we get "Beer" because the age we defined is 26 which is larger than 21

I hope you are able to understand how the ternary operator works but unfortunately if not then please try to run this code once

Once try this code in any JS editor.

AND Operator in React

Syntax

CONDITION  &&  EXPRESSION

The expression will be evaluated as long as the condition is TRUE but if the condition is FALSE then it's not going to evaluate the right-hand side at all means it will return nothing(null) if the condition is false.

SO let's take an example:

import React from "react";

const condition = false;

const currentTime = 13;

function App() {
  return (
    <div className="container">
      {/*Ternary Operator*/}
      {condition ? <h1>Hello</h1> : <h1>I am Umesh</h1>}
      {/*AND Operator*/}
      {currentTime > 12 && <h2>Oh let's take a break</h2>}
    </div>
  );
}

export default App;

I hope this explanation was a little helpful for you ๐Ÿ™‚

Thank you and Happy Coding :)

ย