How to implement conditional rendering in ReactJS?

Reactjs

Front-end web development with ReactJS remained a hot trend in 2020 and is continuing its popularity till now. According to Statista, it is the most used framework among developers worldwide in 2021. If you also prefer ReactJS over other frameworks, enjoy this article; it covers various methods to implement conditional rendering in ReactJS to help you achieve more readable codes.

While developing an application in ReactJS or any other JavaScript library, it is common to deliver elements and components based on certain conditions. This process of providing components as per the use case in hand is called conditional rendering in ReactJS.

Let’s understand this with an example of handling a login and logout button. There will be separate components for both buttons as both have different functions.

 Now take the case-

  • If a user is logged in, we have to render the logout component to display the logout button.
  • Similarly, if the user is not logged in, then, in that case, to show the login button, we will have to render the login component.

In both these situations, we have to render components as per the requirement to display the correct message to users. That is why conditional rendering in ReactJS is used to simplify the code.

In ReactJS, there are various ways to do conditional rendering. Depending upon the problem you want to solve, some are best suited than others. When hiring ReactJS developers, always ensure they apply conditional rendering in the below-given scenarios to deliver more scalable applications.

  • Showing or Hiding elements
  • Implementing permission levels
  • Rendering external data from an API
  • Implementing permission levels
  • Authentication and Authorization

Let’s move on to discover the comprehensive list of conditional rendering in ReactJS withpractices for these patterns.

7 Common Methods of Conditional Rendering in ReactJS

  • Using If
  • Using If else
  • Ternary Operator
  • Switch Case
  • Multiple Conditional Rendering with Enum
  • Logical (&&) Operator
  • Higher-Order component in ReactJS

Let’s dive deeper into all these conditional rendering options in ReactJS and see when and how to apply them.

1. Using IF Statement

Using the ‘if’  statement is the most basic conditional rendering logic in ReactJS. We use the “if” statement when we want to render different components in different situations.

Let’s understand this with an example.

Suppose we want to deliver different messages whenever a user login or logout. For that, we create two functional elements those are:

One element returns the message ‘ Hello Everyone.”

const HelloEveryone = (props) => {
return <h1>Hello Everyone!</h1>;
Another  display the message ‘Welcome you.’
Const  WelcomeMessage = (props) => {
return <h1> Welcome you.</h1>;

Now, to check if the user is logged in and ensure the right message is displayed, we will create a third functional component using the “if” statement, wherein we will take the above two components.

const IsUserLoggedIn = (props) = > {
const  isLoggedIn = props.isLoggedIn;
If (isLoggedIn)  {
return <HelloEveryone  />;
}
return  <WelcomeMessage  />;
}
ReactDOM.render(
<IsUserLoggedIn  isLoggedIn={false}  />,
document.getElementById(‘root’)
);

Features of “If” statement

  •  It’s the most basic conditional rendering.
  • It is utilised to quit right on time from a rendering.
  • It can not be used with JSX and return statements.      

2. Using IF-ELSE Statement

If we want to render a component only when a specific action will happen, this can be done using the “if-else” statement.

See how we use the “if-else” statement in the below example. Only when the user is logged in( specific action)  the logout button will render, while in all other cases, the login button will display.

  render ()  {
      let  {UserIsLoggedIn}  =  this.state;
       const  renderAuthButton = () =>{
            if(UserIsLoggedIn) {
                          return  <button>Logout</button>
                        } else {
                          return  <button>Login</button>
                        }
                   }

Features of IF-ELSE statement

  • It is very wordy; that’s why it is rarely used.
  • It is used when there are two expected outcomes.
  • Likethe “IF” statement, we can’t use it inside JSX and the return statement.

3. Using Ternary operator

The ternary operator is another way of doingan “if-else” statement but in a shorter form. Here the first part states the state condition, and if it is true, the second part is returned,  else the third part is returned. Let’s check how it is done:

  const IsUserLoggedIn = (props) => {
       const isLoggedIn = props.isLoggedIn;
       return (
          <div>
              {isLoggedIn ? (
                 “You are logged in!”
               ) : (
                 “You are logged out!”
               )}
         </div>
        );
     }
ReactDOM.render(
  <IsUserLoggedIn isLoggedIn={false} />,
  document.getElementById(‘root’)
);

In the ternary operator, the parentheses () around both the implicit return statements allow you to return single or multiple components from there. But in the case of a single element, you can omit the parentheses.

Features of Ternary Operator

  •  It is used in situations where there are two expected outcomes.
  •  It can be used inside return statements and JSX
  •  It is generally used in place of “If-else” conditional rendering.

4. Using Switch Case

The switch case conditional rendering  in ReactJS is used for one of the below-given reasons:

  • For multiple values which require the same code.
  • If you are comparing various possible conditions of an expression, which itself is non-trivial.
  • If you have some values which require another value execution.

These reasons depict that we should use a “switch case” conditional rendering when rendering multiple components. Now, to understand it more precisely, let’s take a situation of notification component rendering warning, error, and info component on the basis of status string. Now see how to write code using the “IF” statement and the “switch case” in this situation.

Using “If” conditional rendering we write the code as:

function Notification({ text, status }) {
 if (status === ‘info’) {
   return <Info text={text} />;
 }
 if (status === ‘warning’) {
   return <Warning text={text} />;
 }
 if (status === ‘error’) {
   return <Error text={text} />;
 }
 return null;

 Using switch case conditional rendering, we write the code as:

function Notification({ text, status }) {
 switch (status) {
   case ‘info’:
     return <Info text={text} />;
   case ‘warning’:
     return <Warning text={text} />;
   case ‘error’:
     return <Error text={text} />;
   default:
     return null;
 }
}

ReactJS components always have to return an element or null; hence it is advisable to use the default for the switch case operator.

Although the switch case is a wonderful option for multiple conditional rendering in the ReactJS, it has one drawback: we can not use the switch case with JSX. To overcome this drawback, ‘Multiple Conditional Rendering with Enum’ comes into action.

Features of Switch Case

  • We use it when there are more than two outcomes.
  • Except for the self-invoking function, it can not be used within JSX and return.
  • It is very lengthy; hence developers generally use Enums instead of it.

5. Multiple Conditional Rendering with Enum

In JavaScript, when an object is used as a map of key-value pairs, it is called an enum. An enum is the best way to handle the conditional rendering of multiple components as it can be used within the JSX.

To explain how to use an enum, we will take the same example of the notification component. Here we used enum as an inlined object (Inner curly braces)

function Notification({ text, status }) {
 return (
   <div>
     {
       {
         info: <Info text={text} />,
         warning: <Warning text={text} />,
         error: <Error text={text} />,
       }[status]
     }
   </div>
 );
}

We can also use enum as a constant for condition render and a function to retrieve the value. Have a look at both the situation

Enum as a constant for conditional rendering

Const NOTIFICATION_STATES ={
Info:  <Info />,
Warning:  <Warning />,
Error: <Error />,
};
function Notification({ status }) {
      return (
           <div>
function Notification({ status }) {
 return (
   <div>
      {NOTIFICATION_STATES [status]}
   </div>
 );
}

Creating Enum component which will pass the value of the state to the function(enum state)

class Enum extends React.Component {
  render() {
    return (
      <div>
        <h1>Conditional Rendering with enums</h1>
        <EnumState state=”default”></EnumState>
        <EnumState state=”bar”></EnumState>
        <EnumState state=”foo”></EnumState>
      </div>
    );
  }
}
ReactDOM.render(<Enum />, document.getElementById(“app”));

Features of Enum

  • We use  Enum for conditional rendering in ReactJS based on multiple states.
  • It is mainly used to map more than one condition.
  • It can be used within return statements as well as in JSX.

6. Logical && Operator

Logical && operator is used for checking the condition. It will render the element right after && if the condition is true. While if the condition is false, ReactJS will skip it.

Refer to the below example to understand the behaviours of && operator

(‘welcomehome’ == ‘WelcomeHome’) && alert(‘This alert will never be shown!’)

If you run the above code, the alert message will not be displayed as the condition is not matching.

But you will see the alert message if you run the below code

(5 > 4) && alert(‘This alert will be shown!’) 

import React from ‘react’;  
import ReactDOM from ‘react-dom’;  
// Example Component  
function Example()  
{  
    return(<div>  
            {  
                (10 > 5) && alert(‘This alert will be shown!’) 
            }  
           </div>  
        );  
}  

After looking at these components, we can say that Logical && operator gives more concise results than a ternary operator. That’s why it is also called ‘short circuit evaluation’.

Features of Logical && operator

  • It is best for the situation when there is only an expected outcome.
  • It is also used when one side of the Ternary Operator returns null.
  • It can be used inside return statements and JSX.

7. Using Higher-Order Components

Higher-Order components or HOCs is a function that takes a component and returns it with some added functionality. We can use it for multiple use cases. Out of them, one of the crucial use cases is to change the look of a component with conditional rendering.

Look at the HOC in the below given example, which shows either a desired component or a loading indicator.

    // HOC declaration
            function withLoading(Component) {
                return function EnhancedComponent({ isLoading, …props }) {
                     if (!isLoading) {
                       return <Component { …props } />;
                     }
                    return <div><p>Loading…</p></div>;
                 };
             }
           // Usage
          const ListWithLoading= withLoading(List);
          <ListWithLoading
               isLoading={props.isLoading}
               list={props.list}
          />

Features of Higher-Order Components

  • It is mainly used to shield away multiple conditional rendering.
  • It can return different components based on the conditions.
  • You can use it in the render method passing all the needed properties.

Important checkpoints for successful Conditional Rendering in ReactJS

  • The conditional rendering that is best for your situation is based on:
  • The complexity of the conditional logic
  • Your programming style
  • Your comforts with the JSX, JavaScript, and advanced ReactJS concepts like Higher Order Components (HOC)
  • Do not change the position of components randomly to avert unnecessary unmounting and remounting of the components.
  • Avoid unnecessary bloating of components within the render method, as this will delay components in the rendering process.
  • The markup that is concerned with the conditional rendering makes sure to change that only.

Word From Author

In this article, we have covered multiple ways to do conditional rendering in ReactJS. Each method has its own advantages and helps to achieve more readable code. Depending upon your use case at hand, choose the method which is the best fit for your situation. We believe this article will help simplify your decision; perhaps we are eager to listen to your opinion and suggestions, do reply in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *