React Conditional Rendering Best Practices with 7 Different Methods
Tags: javascript, react, webdev, tutorial
Published: 2020-08-17 16:11:13

This post was originally published at <a href="https://www.devaradise.com/react-conditional-rendering-if-else">https://www.devaradise.com/react-conditional-rendering-if-else</a>

<!-- wp:paragraph -->
<p>In React, conditional rendering can be done in many ways depend on contexts. In this post, we're going to discuss all of the methods that we can use to write better code for conditional rendering in React.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Conditional Rendering is a common feature that exists in every programming language, including javascript. In javascript, we usually write conditional rendering with "if else" statement, "switch case" statement, and ternary operator.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>All of these methods are applicable to React. But the question is, How we can use them effectively?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you might know, React has JSX markup that often we need to implement conditional logic for component there. However, we can't use common "if else" or "switch case" statement directly in JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In JSX, we should use other conditional rendering methods like the ternary operator and &amp;&amp; operator. Here, we are going to discuss this more details.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Related posts:</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><a href="https://www.devaradise.com/react-project-folder-structure">React Project Structure Best Practices for Scalable Application</a></li><li><a href="https://www.devaradise.com/react-infinite-scroll-tutorial" target="_blank" aria-label="undefined (opens in a new tab)" rel="noreferrer noopener">React Infinite Scroll Tutorial</a></li></ul>
<!-- /wp:list -->

~~

<!-- wp:paragraph -->
<p>At least, there are 7 methods of conditional rendering that we can use in React. Each one of them has its own advantage in some contexts.</p>
<!-- /wp:paragraph -->

<div id="ez-toc-container" class="ez-toc-v2_0_11 counter-hierarchy ez-toc-grey"><div class="ez-toc-title-container"><p class="ez-toc-title">Table of Contents</p>
<span class="ez-toc-title-toggle"><a class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle"><i class="ez-toc-glyphicon ez-toc-icon-toggle"></i></a></span></div><nav><ul class="ez-toc-list ez-toc-list-level-1"><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-1" href="#1_Conditional_Rendering_with_If_Else" title="1. Conditional Rendering with If Else">1. Conditional Rendering with If Else</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-2" href="#2_Conditional_Rendering_with_Ternary_Operator" title="2. Conditional Rendering with Ternary Operator">2. Conditional Rendering with Ternary Operator</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-3" href="#3_Conditional_Rendering_with_Shortcircuit_Operator" title="3. Conditional Rendering with Short-circuit &amp;&amp; Operator">3. Conditional Rendering with Short-circuit &amp;&amp; Operator</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-4" href="#4_Multiple_Conditional_Rendering_with_Switch_%E2%80%93_Case" title="4. Multiple Conditional Rendering with Switch – Case">4. Multiple Conditional Rendering with Switch – Case</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-5" href="#5_Multiple_Conditional_Rendering_with_Enum_Object" title="5. Multiple Conditional Rendering with Enum Object">5. Multiple Conditional Rendering with Enum Object</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-6" href="#6_Conditional_Rendering_with_HOC" title="6. Conditional Rendering with HOC">6. Conditional Rendering with HOC</a></li><li class="ez-toc-page-1 ez-toc-heading-level-3"><a class="ez-toc-link ez-toc-heading-7" href="#7_JSX_Conditional_Rendering_with_External_Library" title="7. JSX Conditional Rendering with External Library">7. JSX Conditional Rendering with External Library</a></li></ul></nav></div>

<!-- wp:heading {"level":3} -->
<h3 id="1_Conditional_Rendering_with_If_Else">1. Conditional Rendering with If Else</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best Practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use anywhere outside JSX markup</li><li>Or when you want to execute more than one line of code inside if-else block</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This is the first method that all programmers know, the common if-else statement. We can use it anywhere in a React project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In React, using the common if-else statement is the best when you want to execute more than one line of code inside if or else block, or anywhere outside JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, we want to execute some codes if user is logged in.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
  // * Conditional rendering with common if-else statement.
  if(isLoggedIn) {
    setUserProfile(userData);
    setUserHistory(userHistory);
    // other block of codes;
  }
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Or when you want to define accessible contents based of user role.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
  if(userProfile.role === 'superadmin') {
    initSuperAdminFunction();
    initSuperAdminComponent();
    // other block of codes;
  } else if(userProfile.role === 'admin') {
    initAdminFunction();
    initAdminComponent();
    // other block of codes;
  } else {
    initUserComponent();
    // other block of codes;
  }
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>if you only want to execute one line of code, like calling a function inside if or else block, you can remove the brackets like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
```javascript
if(userProfile.role === 'superadmin')
    initSuperAdminComponent();
else if(userProfile.role === 'admin')
    initAdminFunction();
else 
    initUserComponent();

```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Condition in if-else without brackets only applied to one line of codes right below it.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>If else statement in JSX</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As you might know, we can inject and mix some javascript codes in JSX inside brackets { }. But it has some limitations. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can't inject if-else statement directly to it. Injecting if-else statement in JSX only works with <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE" target="_blank" aria-label="undefined (opens in a new tab)" rel="noreferrer noopener">Immediately Invoked Function Expression (IIFE)</a> like this:</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
return(
    <div>
      { 
        (() => {
          if(isLoggedIn) {
            return (<div>I'm logged in.</div>);
          }
        })()
      }
    </div>
)
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you can see, that's too verbose for just an if statement. That's why i don't recommend using if-else statement inside JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are some other ways for conditional rendering in JSX, just keep reading.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="2_Conditional_Rendering_with_Ternary_Operator">2. Conditional Rendering with Ternary Operator</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use it to assign value for a conditional variable or function return value</li><li>Or when you want to execute only one line of code</li><li>Or for conditional rendering in JSX</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Ternary operator is a shortcut for a common if-else statement. With ternary operator, you can write the conditional rendering inline, or in only one line of code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let’s see the example of conditional rendering for variable value assignment.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
  // 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;
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>And this is conditional rendering example for function return value:</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
// 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;
  }
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you can see, you can shorten if-else statement with just one line with ternary operator.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can also use ternary operator in JSX instead of using if-else with Immediately Invoked Function Expression (IIFE).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's say, we want to render a small component conditionally based on <code>isShow</code> state. You can write the conditional rendering like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
return (
  <div>
     { isShow ? <SmallComponent/> : null }
  </div>
)
```
<!-- /wp:code -->

<!-- wp:heading {"level":4} -->
<h4>if - else if - else with Ternary Operator</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In the example above I only show you how to use a ternary operator to substitute if-else statement.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Ternary operator can also be used to substitute multiple conditional rendering (if - else if - else) or nested conditional rendering. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>However, I don't recommend you to use this as it's harder to read than a common if-else statement. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let' say you want to implement nested conditional rendering in JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
return (
  <div>
    { condition_a
      ? <ComponentA/>
      : ( condition_b
        ? <ComponentB/>
        : ( condition_c
          ? <ComponentC/>
          : <ComponentD/>
        )
      )
    }
  </div>
);
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Look messy, right?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For cases like this, using IIFE, switch-case statement or enum object is better than the ternary operator.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="3_Conditional_Rendering_with_Shortcircuit_Operator">3. Conditional Rendering with Short-circuit &amp;&amp; Operator</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best practice Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use it for a simple conditional rendering that no need to execute code in the 'else' block.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>With ternary operator, you can shorten if-else statement and have better choice for conditional rendering in JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But, do you know that there is a simpler method than ternary operator?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A Short-circuit AND Operator can be used to replace an if statement like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
// Instead of using ternary operator,
{ isShow ? <SmallComponent/> : null }

// Use short-circuit &amp;&amp; operator
{ isShow &amp;&amp; <SmallComponent/> }
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In Ternary operator, even when you have no 'else' condition, you should keep write ': null' expression to avoid error.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>With short-circuit &amp;&amp; operator, you don't have to do that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But, keep in mind that short-circuit &amp;&amp; operator can not be used to substitute an if-else statement, let alone an if-else if-else statement.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="4_Multiple_Conditional_Rendering_with_Switch_–_Case">4. Multiple Conditional Rendering with Switch - Case</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best Practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use it anywhere for multiple conditional rendering that only has one variable to evaluate condition.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Like if-else statement, switch-case statement is also a common feature in almost every programming language.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It is used for multiple conditional rendering with the same type of condition.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, we can use a switch-case statement to render a specific variable value based on user roles.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
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.
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can also use a switch-case statement for conditional rendering in JSX. However, you should wrap it inside IIFE.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Suppose that you want to render an alert component that styled based on the alert status.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
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>
)
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you might have noticed, both examples have only one variable (<code>role</code> and <code>status</code>) to evaluate conditions. This is what I called the same type of conditions before.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Switch-case statement can not be used to handle a complex and different type of conditions. Instead, you should use a common if-else if-else statement for that.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="5_Multiple_Conditional_Rendering_with_Enum_Object">5. Multiple Conditional Rendering with Enum Object</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best Practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use it only when you want to assign variable value or return value with multiple conditions.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Enum objects can also be used to implement multiple conditional rendering in React. It is the better alternative for switch-case statements in JSX markup.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you know before in the 5th method, you should wrap the switch-case statement inside IIFE in JSX. With an enum object, you don't need to do that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take the same example as before. You want to render an alert component based on status. Here is how you conditionally render it using an enum object.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
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>
)
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>As you can see, you need to create an enum object first called 'ALERT_STATUS'. Then, simply call it in JSX with <code>status</code> variable inside elbow bracket that has value 'warning', 'error', 'success' or 'info'.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If the <code>&lt;AlertComponent/></code> need other props or attributes to be passed, you can change <code>ALERT_STATUS</code> to a function like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
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>
)
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>You can also assign the alert component to a variable.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
let newVariable = ALERT_STATUS(messageState)[status];
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Of course, you should define the enum object first.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Separating Enum object as file to make it reusable </h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The best thing about using an Enum object for conditional rendering is that you can make it reusable.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Back to the example case, the Alert component is a component in React that usually reusable. So, you can also make it reusable when you want to render it conditionally.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can define the enum in seperate file and export it like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
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}/>
})
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Then, import it when you want to use it in a component.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
import { ALERT_STATUS } from './alertStatus'
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The usage is the same as before.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="6_Conditional_Rendering_with_HOC">6. Conditional Rendering with HOC</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best Practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Use it when you want to implement or check some conditions before rendering a component.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Higher Order Component (HOC) can be used to implement conditional rendering in React. You can use it when you want to run some logic or checking before rendering a component.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For example, you want to check if the users are authenticated before they access some components.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Instead of writing if-else statement in every component that needs authentication, you can use HOC to guard those component.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
// 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>);
    }
  }
}
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Then, you can import and use it in a component.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
import withAuthentication from './withAuthentication'
```
<!-- /wp:code -->

<!-- wp:code {"lineNumbers":true} -->
```javascript
const AuthenticatedUIComponent = withAuthentication(AnUIComponent);

return (
  <div>
    <AuthenticatedUIComponent/>
  </div>
)
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>That's better, right?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can use HOC for other reusable conditional rendering like loading indicator implementation, null checking, etc.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>To more details about HOC (with functional component), you can <a href="https://medium.com/@albertchu539/higher-order-components-in-a-react-hooks-world-69fe1f0b0791" target="_blank" aria-label="undefined (opens in a new tab)" rel="noreferrer noopener nofollow">read this article on medium</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3 id="7_JSX_Conditional_Rendering_with_External_Library">7. JSX Conditional Rendering with External Library</h3>
<!-- /wp:heading -->

<!-- wp:heading {"level":4} -->
<h4>Best Practices Summary</h4>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li>Avoid using this method. Be familiar with the 6 methods above :D</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Though I wouldn't recommend you using this method, I just want to let you know that there is a babel plugin that makes JSX have its own conditional rendering tags.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>with <a aria-label="undefined (opens in a new tab)" href="https://github.com/AlexGilleran/jsx-control-statements" target="_blank" rel="noreferrer noopener nofollow">JSX Control Statements</a>, you can write conditional rendering in JSX like this.</p>
<!-- /wp:paragraph -->

<!-- wp:code {"lineNumbers":true} -->
```javascript

<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>
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>In the compilation, those tags will be transformed into ternary operators.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Some developers use this plugin because it looks more readable for conditional rendering in JSX.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph {"align":"center"} -->
<p class="has-text-align-center">~~</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's all the 7 methods you can use for conditional rendering in React. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Do you know other methods for conditional rendering in React? or some thoughts about the methods above?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Feel free to suggest it in the comment below!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Happy coding!</p>
<!-- /wp:paragraph -->