SoFunction
Updated on 2025-03-10

React conditional rendering best practice summary (7 types)

In React, conditional rendering can be used in many ways, and different usage scenarios depend on different contexts. In this article, we will discuss all the ways you can use to write better code for conditional rendering in React.

Conditional rendering is a common feature in every programming language, including javascript. In javascript, we usually write conditional rendering using if else statement, switch case statement and ternary operator.

All of the above methods work for React. But the question is, how can we use them effectively?

As you know, React has JSX tags, and we usually need to implement conditional logic to control components. However, we cannot directly use common if else or switch case statements in JSX.

In JSX, we should use other conditional rendering methods, such as the ternary operator and the && operator. Here we will discuss more details.

Here are 7 conditional rendering methods I have accumulated that can be used in React. Each method has its own advantages under certain circumstances.

Table of contents

  • If Else conditional rendering
  • Conditional Rendering with ternary operators
  • Conditional rendering of && operator
  • Multi-condition rendering with switch case
  • Multi-condition rendering of enumerated objects
  • HOC (high-order component) conditional rendering
  • JSX conditional rendering with external libraries

Else conditional rendering

Best Practice Overview

  • Use anywhere outside of JSX tags
  • Or, if you want to execute multiple lines of code in the if-else block

This is the first method that all programmers can think of, namely the common if-else statement. We can use it anywhere in our React project.

In React, if you want to execute multiple lines of code inside an if or else block or anywhere outside of JSX, it is best to use a common if-else statement.

For example, if the user is logged in, we want to execute some code.

// * Conditional rendering with common if-else statement.
if (isLoggedIn) {
 setUserProfile(userData);
 setUserHistory(userHistory);
 // other block of codes;
} 

Or, when you want to define accessible content based on user roles.

if ( === "superadmin") {
 initSuperAdminFunction();
 initSuperAdminComponent();
 // other block of codes;
} else if ( === "admin") {
 initAdminFunction();
 initAdminComponent();
 // other block of codes;
} else {
 initUserComponent();
 // other block of codes;
} 

If you want to execute only one line of code, such as calling a function in an if or else block, you can remove the brackets.

if ( === "superadmin") initSuperAdminComponent();
else if ( === "admin") initAdminFunction();
else initUserComponent(); 

The condition without brackets in if-else only applies to a line of code directly below it.

If else statement in JSX

As you probably know, we can inject and mix some javascript code into square brackets {} in JSX. But it has some limitations.

You cannot directly insert an if-else statement into it. Injecting an if-else statement in JSX only works for calling function expressions (IIFE) immediately, as shown below:

return (
 <div>
  {(() => {
   if (isLoggedIn) {
    return <div>I'm logged in.</div>;
   }
  })()}
 </div>
); 

As you can see, if statements alone are too verbose. This is why I don't recommend using if-else statements in JSX.

Continue reading There are some other methods for conditional rendering in JSX.

2. Use ternary operators for conditional rendering

Best Practice Overview

  • Conditional variable or function return value assignment
  • When you only want to write a line of code to make conditional judgments
  • Conditional Rendering in JSX

The ternary operator is a shortcut to common if-else statements. Using the ternary operator, you can write conditional rendering in the line or just one line of code.

Let's look at the example of variable value allocation for conditional rendering.

// Conditional rendering with common if else
let isDrinkCoffee;
if (role === "programmer") {
 isDrinkCoffee = true;
} else {
 isDrinkCoffee = false;
}

// Conditional rendering with ternary operator
let isDrinkCoffee = role === "programmer" ? true : false; 

Here is a conditional rendering example of the function return value:

// Conditional rendering with common if else
function isDrinkCoffee(role) {
 if (role === "programmer") {
  return true;
 } else {
  return false;
 }
}

// Conditional rendering with ternary operator
function isDrinkCoffee(role) {
 return role === "programmer" ? true : false;
} 

As you can see, if you use the ternary operator, you use a line of code instead of the if-else statement.

You can also use ternary operators in JSX instead of using if-else with call function expressions immediately (IIFE).

Suppose we want to render a widget conditionally based on the isShow state. You can write conditional rendering like this.

return <div>{isShow ? <SmallComponent /> : null}</div>;

if-else if-else uses ternary operator

In the example above, I'll just show you how to replace the if-else statement with the ternary operator.

The ternary operator can also be used to replace multiple conditional renderings (if-else if-else) or nested conditional renderings.

However, I don't recommend you to use it because it's harder to read than the normal if-else statement.

Suppose you want to implement nested conditional rendering in JSX.

return (
 <div>
  {condition_a ? (
   <ComponentA />
  ) : condition_b ? (
   <ComponentB />
  ) : condition_c ? (
   <ComponentC />
  ) : (
   <ComponentD />
  )}
 </div>
); 

It looks very messy, right?

For this case, using IIFE, switch-case statements, or enumeration objects is better than ternary operators.

3. Conditional rendering of && operators

Best Practice Overview

  • Use it for simple conditional rendering without having to execute the code in the "else" block.

Using the ternary operator, you can shorten the amount of code for an if-else statement and provide a better option for conditional rendering in JSX.

But, do you know there is an easier way than a ternary operator?

The && operator can be used to replace such if statements.

// Instead of using ternary operator,
{
 isShow ? <SmallComponent /> : null;
}

// Use short-circuit && operator
{
 isShow && <SmallComponent />;
} 

In ternary operators, even if there is no "else" condition, a "null" expression is required to avoid syntax errors.

Using the && operator, you don't need to write extra code.

However, remember that you cannot replace the && operator with an if-else statement, let alone if-else if-else statement.

4. Multi-condition rendering with switch-case

It can be used anywhere to make multiple conditional renderings, and only one variable can determine the condition.

Like the if-else statement, the switch-case statement is also a common feature in almost every programming language.

It is used for multiple conditional renderings with the same type of conditions.

For example, we can use the switch-case statement to present specific variable values ​​based on user roles.

let welcomeMessage;
switch (role) {
 case "superadmin":
  welcomeMessage = "Welcome Super Admin";
 // you can put other codes here as well.
 case "admin":
  welcomeMessage = "Welcome Admin";
 // you can put other codes here as well.
 case "user":
  welcomeMessage = "Welcome User";
 // you can put other codes here as well.
 default:
  welcomeMessage = "Welcome Guest";
 // you can put other codes here as well.
} 

You can also use the switch-case statement to perform conditional rendering in JSX. However, you need to wrap it in IIFE.

Suppose you want to render an alert component that styles based on the alert state.

return (
 <div>
  {(() => {
   switch (status) {
    case "warning":
     return <AlertComponent status="warning" message={messageState} />;
    case "error":
     return <AlertComponent status="error" message={messageState} />;
    case "success":
     return <AlertComponent status="success" message={messageState} />;
    default:
     return <AlertComponent status="info" message={messageState} />;
   }
  })()}
 </div>
); 

You may have noticed that both examples have only one variable (role and status) to judge the condition. This is the same type of condition I mentioned before.

The switch-case statement cannot be used to deal with complex and different types of conditions. But you can use the general if-else statement to handle those scenarios.

5. Multiple conditional rendering of enumerated objects

Use it only if you want to assign a variable value or return value with multiple conditions.

Enumerated objects can also be used to implement multiple conditional renderings in React. It is a better choice for switch-case statements in JSX tags.

As you know, in method 5, you should wrap the switch-case statement in IIFE of JSX. Using enum objects, you don't need to do this.

Let's use a previous example to distance. You want to render the alert component based on the status. This is how an enum object is rendered conditionally.

const ALERT_STATUS = {
 warning: <AlertComponent status="warning" />,
 error: <AlertComponent status="error" />,
 success: <AlertComponent status="success" />,
 info: <AlertComponent status="info" />,
};

return <div>{ALERT_STATUS[status]}</div>; 

You need to create an enum object, first called "ALERT_STATUS". Then, just call it in JSX using the state variable inside the [] brackets, which has the value of 'warning', 'error', 'success', or 'info'.

If you need to pass other props or attributes, you can change ALERT_STATUS to a function like this.

const ALERT_STATUS = (message) => ({
 warning: <AlertComponent status="warning" message={message} />,
 error: <AlertComponent status="error" message={message} />,
 success: <AlertComponent status="success" message={message} />,
 info: <AlertComponent status="info" message={message} />,
});

return <div>{ALERT_STATUS(messageState)[status]}</div>; 

You can also pass variables to the alert component.

let newVariable = ALERT_STATUS(messageState)[status];

Of course, you should first define the enum object.

Split the enum object into a separate file for reuse

The best feature about conditional rendering using enum objects is that it can be reused.

Going back to the example case, the Alert component is a commonly reusable component in React. Therefore, when you want to render it conditionally, you can also let it reuse.

You can define an enum in a separate file and export it.

import React from "react";
import AlertComponent from "./path/to/AlertComponent";

export const ALERT_STATUS = (message) => ({
 warning: <AlertComponent status="warning" message={message} />,
 error: <AlertComponent status="error" message={message} />,
 success: <AlertComponent status="success" message={message} />,
 info: <AlertComponent status="info" message={message} />,
}); 

Then, import it when you want to use it in the component.

import { ALERT_STATUS } from "./alertStatus";

The usage is the same as before.

Conditional Rendering

Best practice summary

Use it if you want to implement or check certain conditions before rendering a component.

Advanced Order Components (HOCs) can be used to implement conditional rendering in React. You can use it when you want to run some logic or check before rendering the component.

For example, you want to check if the user is authenticated before accessing certain components.

Instead of writing if-else statements in every component that requires authentication, you can use HOC to protect those components.

// This is Higher Order Component
import React from "react";
export default function withAuthentication(Component) {
 // some code of authentication logic/service that result an isLoggedIn variable/state:
 let isLoggedIn = true;

 return function AuthenticatedComponent(props) {
  if (isLoggedIn) {
   return <Component {...props} />;
  } else {
   return <div class="alert alert-danger">You're not authenticated!</div>;
  }
 };
} 

You can then import it and use it in the component.

import withAuthentication from "./withAuthentication";
const AuthenticatedUIComponent = withAuthentication(AnUIComponent);

return (
 <div>
  <AuthenticatedUIComponent />
 </div>
); 

This is even better, isn't it?

You can use HOC for other reusable conditional renderings, such as load indicator implementations, null value checking, etc.

More details about HOC (with functional components) can be found in medium (/@albertchu539/higher-order-components-in-a-react-hooks-world-69fe1f0b0791)。

7. JSX conditional rendering with external libraries

Best practice summary

  • Avoid using this method. Familiar with the above 6 methods: D

Although I don't recommend you to use this method, I just want you to know that there is a babel plugin that makes JSX have its own conditional rendering tags.

Using JSX control statements, you can write conditional rendering in JSX like this.

<If condition={test}>
 <span>Truth</span>
</If>;

<Choose>
 <When condition={test1}>
  <span>IfBlock</span>
 </When>
 <When condition={test2}>
  <span>ElseIfBlock</span>
  <span>Another ElseIfBlock</span>
  <span>...</span>
 </When>
 <Otherwise>
  <span>ElseBlock</span>
 </Otherwise>
</Choose>; 

In compilation, these tags are converted to ternary operators.

Some developers use this plugin because it looks more readable for conditional rendering in JSX.

Translator's note: You can also implement a simple IF component to implement simple judgment.

const If = (props) => {
 const condition =  || false;
 const positive =  || null;
 const negative =  || null;

 return condition ? positive : negative;
}; 

&lt;IF condition={isLoggedIn} then={&lt;Hello /&gt;} else={&lt;div&gt;Please log in first&lt;/div&gt;} /&gt;

Here are all 7 ways you can use for conditional rendering in React.

Happy coding!

Translation from/syakirurahman/react-conditional-rendering-best-practices-with-7-different-methods-16e3#6_Conditional_Rendering_with_HOC
Original author Syakir Rahman

Translator: Blue autumn wind (github/hua1995116)

This is the end of this article about the best practice summary of React conditional rendering (7 types). For more related React conditional rendering content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!