React Conditional Rendering with AND operator

React Conditional Rendering with Examples

ยท

2 min read

React Conditional Rendering with AND operator

Introduction

Since I started my React journey I have noticed many people use Else or ternary operators for conditional rendering.

But many do not know that The '&&' or 'AND' operator can also be used for conditional rendering.

in this blog, ill tell you 'Why', 'How', and 'When' to use the AND operator.

  1. What is an AND operator
  • A practical guide to its usage

  • How to use this in React

OR long story short

Perfection.png

1. What is the AND operator

Definition: The logical AND (&&) operator (logical conjunction) for a set of operands is true if and only if all of its operands are true Notation for AND operator: && can read more about AND operator Here

2. Practical Guide

in our case, we are using one feature of it that is

  • when we join multiple statements with '&&'

  • it will run the code from 'left to write'

// example
true && "ok" && console.log("HI") ;
expected output: Ok Hi
  • and if any false statement occurs it will just stop the execution of that line.

let's understand by example

true && console.log('ok')
// expected output: ok
false && console.log('ok')  
// expected output: false 
// hence nothing will render in reacts DOM for this line

More Examples

true && console.log('ok') && true && console.log('Hi')
// Expected Output: ok Hi

true && console.log('ok') && false && console.log('Hi')
// Expected Output: ok
// Here the code stops at the 'false' statement and doesn't move furthur

3. How to use this in React

Let's take a use case,

  • I want to Display the user name in my header if a user is Authenticated.

now let's Assume a Function is authenticated() that returns true if a user is authenticated and wise versa

let's code it



//... this is a sudo code ok.
<div>
{ isAuthaticated() && <UserName name={user.Name} }
<div>
//....


/* if (isAuthaticated is true)
            than userName will we returned
    else 
            it will just skip the line
 */

That's it now go ahead and spam && operator in your code everywhere ๐Ÿ˜‹.

4. When should I use && operator ๐Ÿค”

  1. The rule of thumb is when you don't have an 'else' statement.
ย