4 Ways to Conditionally Render in React

Intro

If you’re a React developer, you’ve probably dealt with rendering something based on a condition. This process is called conditional rendering, and it’s generally used in the following processes:

  • Showing/hiding an element: Like a button. Does the user have permission to perform this operation by pressing it?
  • Implementing permission: Maybe you have roles in your product. A manager of a store can use their internal app to order new supplies for it, while a cashier doesn’t even see that function in the app.
  • Managing loaders: Easy — the list stops loading its element, we make the load bar disappear.

But it’s not always that easy to handle conditional rendering. Should you use a ternary operator? A couple of &&s or an if statement?

This article will give you different techniques to render something in React based on a condition.

1. Using If..else

Say you’re writing an application for managing technical devices in a physical storage area. You can move one of them to the inventory only when isManager is true. Otherwise, a normal user of the app can ask for support. Suppose you show a button to allow this activity to the correct user:

import React from "react";

export default function StorageManager(props) {
  const { isManager } = props; // will use this prop for managing rendering
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      <button>Move to inventory</button>
    </div>
  );
}

Right now, the option for moving a device to the inventory is always on. Let’s change this with an if ..else statement. This is a trivial task. Simply take the statement out of the render function and calculate the result like this:

import React from "react";

export default function StorageManager(props) {
  const { isManager } = props;
  let operationButton;
  if (isManager) {
    operationButton = <button>Move to inventory</button>;
  }
  else {
    operationButton = <button>Ask for support</button>;
  }

  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {operationButton}
    </div>
  );
}

Please check out this link for more information about why you can’t use an if ..else statement directly inside JSX. But, just for notice, you may prefer a more concise inline solution to this problem using this IIFE approach:

import React from "react";

export default function StorageManager(props) {
  const { isManager } = props;

  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {(() => {
        if (isManager) {
          return <button>Move to inventory</button>
        } else {
          return <button>Ask for support</button>
        }
      })()}
    </div>
  );
}

There are obvious situations where your code will be a lot more complicated than this. What if you have to perform some preliminary operations before allowing a device to move to the inventory? Like checking whether there’s enough space, or when new space will be available. In these cases, you could separate this logic and wrap it in a helper function or a new component.

Here is the first approach, wrapping it in a helper function:

import React from "react";

function checkPermission(props) {
  // a lot of complex operations go here
  const { isManager } = props;
  if (isManager) {
    return <button>Move to inventory</button>;
  } else {
    return <button>Ask for support</button>;
  }
}

export default function StorageManager(props) {
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {checkPermission(props)}
    </div>
  );
}

Here is the second approach, creating a new component in a new file:

import React from "react";

// authButton.jsx
export default function authButton(props) {
  return (
    <div>
      // logic goes here
    </div>
  );
}

Then simply use it:

import React from "react";
import AuthButton from '../authButton';

// StorageManager.jsx

export default function StorageManager(props) {
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      <authButton isManager={props.isManager}/>
    </div>
  );
}


2. Using a Switch Statement

If you’re comparing many values with a constant, then it might be the case to convert your complicated if ..else clause to a switch statement. I recommend you read this article to learn how to avoid using such a statement and why. For now, let’s just see how you can use it here:

import React from "react";

function checkPermission(props) {
  switch(props.isManager) {
    case true:
      return <button>Add to inventory</button>;
    case false: 
      return <button>Ask for support</button>;
    default: 
      return null;
  }
}

export default function StorageManager(props) {
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {checkPermission(props)}
    </div>
  );
}

Note how returning null will render nothing where we call checkPermission() which is quite helpful in this case.

3. Using a Ternary Operator

This is probably the way you will go with conditional rendering most of the time. Why? Because it’s inline, easy to read, and quite concise. Just take a look:

import React from "react";

export default function StorageManager(props) {
  const { isManager } = props
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {isManager 
        ? <button>Add to inventory</button> 
        : <button>Ask for support</button>
      }
    </div>
  );
}

Use the ternary operator when you have to perform a simplified if ..else clause, where, on a condition happening, you return a value. Notice how it is performed automatically without you needing to type return.

4. Short Circuit Evaluation Using &&

This technique is used to ensure that no side-effects occur during operands evaluation in an expression. When you may want to use it? The answer is: when you want something to happen only on a specific condition, otherwise do nothing. Suppose you just want to show the move to the inventory button if the user is a manager:

import React from "react";

export default function StorageManager(props) {
  const { isManager } = props
  return (
    <div>
      <h1>Implementing conditional rendering</h1>
      {isManager && <button>Add to inventory</button>}
    </div>
  );
}

Conclusion

In this article you’ve seen several useful ways to perform conditional rendering in your apps. Usually, my suggestions are:

  • If you have a simple if ..else , then go with a ternary operator.
  • If you want to print something only and only on a certain condition, then go with short-circuit evaluation.
  • For more complex conditions a helper function will usually do the job. But sometimes they grow so much that you’d be better off implementing a new component with its own logic.

Of course, this is just my opinion on a complex topic. Hopefully, this article helped you discover something new and become a better developer.

scr 4 Ways to Conditionally Render in React


author Piero Borrelli, @Twitter


illustration stackoverflow.com