Conditional Rendering in React js - Functional Component

fc-cr


So, try spending the right amount of time optimizing your code while always pushing to reuse components as much as possible. It will help you strike the right balance between quality and shipping time.

1. if-else, having boolean data type value..

We can apply the if-else conditional logic to JSX in React. Remember, JSX is compiled to JS before being executed, so we are literally writing in JS code.

 
 import React from 'react';

  var myName = true;

  function App() {
    if(myName){
      return(
        <div>
          <h2>My Nam is CGVA</h2>
        </div>
      )
    }else{
      return(
        <div>
          <h2>I am react js</h2>
        </div>
      )
    }
  }

  export default App;


if - else in useState(); Hook

 
  import React,{useState} from 'react';

  function App() {
    var [firstName, secName] = useState(false);

    if(firstName){
      return(
        <div>
          <h2>this is first name</h2>
        </div>
      )
    }else{
      return(
        <div>
          <h2>
            this is second name
          </h2>
        </div>
      )
    }

  }

  export default App;


Use Ternary operator, instead of if, else.

Ternary operator is a shorter form of the ‘if-else’ condition. The first part states the condition, the second part is the returned value if true and the last part is the returned value if false.

 
 import React, { useState } from 'react';

  function App() {
    var [firstName, secName] = useState(true);

    return(
      <div>
        {
          firstName ? <h2>my name is CGVA </h2> : <h2>my name is react js</h2>
        }
      </div>
    )
  }

  export default App;