React Conditional Rendering

Back to home
Logicmojo - Updated Aug 28, 2021



What do you mean by React Conditional Rendering?

We can use React to create numerous components that contain the behaviour we require. Then, depending on specific conditions or the status of our application, we can render them. In other words, a component determines which elements it will return based on one or more circumstances. Conditional rendering in React operates in the same way that conditions do in JavaScript. We construct items expressing the current state using JavaScript operators, and then React Component updates the UI to match them.
We can see how conditional rendering works by looking at the example. Consider how to deal with a login/logout button. Separate components will be used for the login and logout buttons. Render the logout component to show the logout button if a user has logged in. Render the login component to show the login button if the user is not logged in.

In React, conditional rendering may be done in a variety of ways. Below is a list of them.

🚀 if
🚀 switch case operator
🚀 ternary operator
🚀 Conditional Rendering with enums
🚀 logical && operator

We will discuss them one by one in brief,

if

The render method in React is the simplest approach to implement conditional rendering. It is limited to the component's entire block. If the condition is true, the element to be rendered will be returned. In the sample below, you can see how it works.


     function temp1(props) {  
      return <h1>Hey Welcome!</h1>;  
     }  
     
     function temp2(props) {  
      return <h1>How are you!</h1>;  
     }  
     
     function temp3(props) {  
      const ischeck = props.ischeck;  
      if (ischeck) {  
        return <temp1 />;  
      }  
      return <temp2 />;  
     }  
      
    ReactDOM.render(  
      <temp3 ischeck={false} />,  
      document.getElementById('root')  
    );  



Logical && operator

The logical && operator can be combined with a condition to determine what will show in the output based on whether the condition evaluates to true or false. The syntax for utilising the logical && operator with conditions is as follows:

{
    condition &&
    
    //This section will contain elements that 
    //will be returned as part of the output. 
}



If the condition in the preceding syntax evaluates to True, the items immediately following the && operator will be included in the output; if the condition evaluates to False, the code within the curly brackets will not be included.



Example :

    import React from 'react';   
    import ReactDOM from 'react-dom';   

    function temp()   
    {   
        return(<div>   
                {   
                    (230 > 455) && alert('Hey Welcome to Logicmojo')  
                }   
               </div>   
            );   
    }   



The alert message is successfully presented on the screen as the condition (230 > 455) evaluates to true, as shown in the above result.

Ternary operator

When two blocks alternate under a particular condition, the ternary operator is utilised. This operator reduces the length of your if-else sentence. It's a shortcut for the if statement that takes three operands.

{
        condition expression ?  statement1 : statement2 
}



Statement1 will be given if the condition is true. False will be returned if this is not the case.



Example :

    temp() {  
    const ischeck = this.state.temp1;  
      return (  
        <div>  
          Welcome {ischeck ? 'Hello!' : 'Hey!'}.  
        </div>  
      );  
    }  



Switch case operator

It's feasible to have many conditional renderings in some cases. Conditional rendering is used in the switch situation based on a different state.



Example :

    function temp({msg}) {  
      switch(msg) {  
        case 'Hey':  
          return <Input text is {msg} />;  
        case 'Welcome to Logicmojo':  
          return <Input text is {msg} />;  
        default:  
          return null;  
      }  
    }  



Conditional Rendering with enums

In some cases, a React Js developer must render and hide components depending on the situation. For example, when developing a to-do list app, the developer must render tasks if any pending tasks are accessible; otherwise, a message such as "There is no pending task available" must be displayed.
In react Js, you can use if-else, ternary operators, and other ways to render components conditionally. Developers can utilise the if-else or switch case methods if just 2 to 3 components are available to render conditionally. If there are more than three components to render conditionally, the if-else statement becomes more complicated. As a result, developers should use enums to keep their code tidy.



Example :

    function msg({ temp1, temp2 }) {  
      return (  
        
{{ msg1: <Message text={temp1} />, }[temp2]}
); }



Preventing Component form Rendering

It's possible that a component will hide itself even if another component rendered it. We'll have to return null instead of the render result to do this (prevent a component from rendering). In the sample below, you can see how it works.



Example :

import React from 'react';   
import ReactDOM from 'react-dom';
 
function temp(props)
{
    if(!props.fun)
        return null;
    else
        return <h1>Welcome to Logicmojo</h1>;
}
 
ReactDOM.render(
    <div>
        <temp fun = {true} />
        <temp fun = {false} />
    </div>,
    document.getElementById('root')
);



Output :

Welcome to Logicmojo



The temp component is drawn twice in the above result, but the <h1> element is only rendered once because null is returned as the rendering output on the second render of the temp component.

Conclusion: So there you have it, your journey into the React Conditional Rendering.