Conditional Rendering in React.js

In react we can create many components which encapsulates the behaviors that are needed. Then we can render them according to the conditions or state of the application. Conditional rendering works like conditions in JavaScript. JavaScript operators are used here to create elements that represent the current state of applications. React Components update the UI to match them. Here we will see an example of login and logout buttons. Login and logout will be two different components. If the user is logged in, the logout component is rendered to display it in the application. Similarly if the user is logged out, the log in component is rendered to display the login button. This is called conditional rendering.  There are different ways to implement this.

If 

Ternary operator

Logical && operator

Switch case operator

Conditional Rendering with enums

1.Using if condition


function UserLoggin(props) {  

  return <h1>Welcome back!</h1>;  

}  

function GuestLoggin(props) {  

  return <h1>Please sign up.</h1>;  

}  

function SignUp(props) {  

  const isLoggedIn = props.isLoggedIn;  

  if (isLoggedIn) {  

    return <UserLogin />;  

  }  

  return <GuestLogin />;  

}  

  

ReactDOM.render(  

  <SignUp isLoggedIn={false} />,  

  document.getElementById('root')  

);


2.Using logical && operator.

Syntax:

{  

    condition &&  

    // whatever written after && will be a part of output.  

}

Example:

import React from 'react';   

import ReactDOM from 'react-dom';   

// Example Component   

function Example()   

{   

    return(<div>   

            {   

                (10 > 5) && alert('This alert will be shown!')  

            }   

           </div>   

        );   

}

3. Using ternary operator.

It is used in cases where two blocks alternate given conditions.

Syntax:

condition ?  true : false 

Example:


render() {  

  const isLoggedIn = this.state.isLoggedIn;  

  return (  

    <div>  

      Welcome {isLoggedIn ? 'Back' : 'Please login first'}.  

    </div>  

  );  

4. Using Switch case operator

When there are many conditional renderings we can use switch cases.

function NotificationMsg({ text}) {  

  switch(text) {  

    case 'Hi All':  

      return <Message: text={text} />;  

    case 'Hello JavaTpoint':  

      return <Message text={text} />;  

    default:  

      return null;  

  }  

5. Using enums

When there are multiple conditional rendering we can use enum which is more readable compared to switch case operators. 

function NotificationMsg({ text, state }) {  

  return (  

    <div>  

      {{  

        info: <Message text={text} />,  

        warning: <Message text={text} />,  

      }[state]}  

    </div>  

  );  

}