Best practice of react conditional rendering (7 methods)

Time:2021-2-19

In react, conditional rendering can be used in many ways. Different ways of using the scene depend on different contexts. In this article, we’ll discuss all the ways you can use to write better code for conditional rendering in react.

~~

Conditional rendering is a common function in every programming language (including JavaScript). In JavaScript, we usually useif elsesentence,switch caseStatement and ternary operator to write conditional rendering.

All of these methods are suitable for react. But the question is, how can we use them effectively?

As you know, react hasJSXTag, usually we need to implement conditional logic to control components. But we can’t be hereJSXUsing commonif elseorswitch casesentence.

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 seven conditional rendering methods I have accumulated, which can be used in react. Each way has its own advantages under certain circumstances.

catalog

  • If Elseconditional rendering
  • Conditional rendering using ternary operators
  • &&Conditional rendering of operators
  • beltswitch caseMulti condition rendering
  • Multi condition rendering of enumeration objects
  • Hoc (high order component) conditional rendering
  • JSX conditional rendering with external library

1.If Elseconditional rendering

Best practice overview

  • Use anywhere other than JSX tags
  • Or, if you want to execute multiple lines of code in an if else block

~~

This is the first method that all programmers can think of, which is commonif-elsesentence. We can use it anywhere in the react project.

In react, if you want to execute multiple lines of code anywhere inside the if or else block or outside JSX, you’d better use the general if else statement.

For example, if the user logs 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 (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;
} 

If you just want to execute a line of code, such as calling functions in if or else blocks, you can delete brackets.

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

The condition without parentheses in if else applies only to the line directly below it.

If else statement in JSX

As you may know, we can inject and mix some JavaScript code into the brackets {} in JSX. But it has some limitations.

You can’t insert an if else statement directly into it. Injecting if else statements into JSX is only applicable to immediate call function expressions (Iife), as follows:

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

As you can see, the if statement alone is too long. That’s why I don’t recommend using if else statements in JSX.

Read on to JSX for other conditional rendering methods.

  1. Conditional rendering using ternary operators

Overview of best practices

  • Assignment of return value of conditional variable or function
  • When you just want to write one line of code to make conditional judgments
  • Conditional rendering in JSX

Ternary operator is a shortcut to common if else statements. With ternary operators, you can write conditional rendering within a line or just one line of code.

Let’s take a look at an example of variable value assignment 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; 

This is an example of conditional rendering of function return values:

// 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, use one line of code insteadif-elsesentence.

You can also use ternary operators in JSX instead of using if else with immediate call function expressions (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-elseUsing ternary operators

In the above example, I’ll just show you how to use ternary operators instead of if else statements.

Ternary operators can also be used to replace multiple conditional renderings(if-else if-else)Or nested conditional rendering.

But I don’t recommend you to use it because it’s better than ordinaryif-elseSentences are harder to read.

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, doesn’t it?

In this case, it is better to use Iife, switch case statements or enumeration objects than ternary operators.

3. Conditional rendering of the & & operator

Overview of best practices

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

~~

Using ternary operators can shorten the code amount of if else statements, and provide a better choice for conditional rendering in JSX.

But do you know a simpler way than ternary operators?

&&Operators 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, you need to write a “null” expression to avoid syntax errors.

With the & operator, you don’t need to write extra code.

Remember, however, that you cannot replace the & & operator withif-elseStatement, not to mentionif-else if-elseSentence.

4. Multi condition rendering with switch case

  • It can be used anywhere for multiple conditional rendering, and only one variable can determine the condition.

~~

imageif-elseLike a sentence,switch-caseStatement is also a common function in almost every programming language.

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

For example, we can useswitch-caseStatement presents a specific variable value based on the user role.

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 useswitch-caseStatement for conditional rendering in JSX. However, you need to package it in Iife.

Suppose you want to present aalertStatus setting stylealertComponents.

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>
); 

As you may have noticed, both examples have only one variable(roleandstatus)To judge the conditions. This is the same type of condition I mentioned earlier.

switch-caseStatement cannot be used to handle complex and different types of conditions. But you can use genericif-else if-elseStatement to deal with those scenes.

5. Enumerate multiple conditional rendering of objects

  • Use it only if you want to assign a variable value or return value with more than one condition.

~~

Enumeration objects can also be used to implement multiple conditional rendering in react. For theswitch-caseStatement, which is a better choice.

As you know, in method 5, you shouldswitch-caseStatements are packaged in Iife of JSX. Using enumeration objects, you don’t have to.

Let’s use a previous example to illustrate the distance. You need to render alert components based on state. This is how enumeration objects are conditionally rendered.

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 enumeration object called “alert” first_ STATUS”。 Then, just use it in JSX[]The value of this variable is’ warning ‘,’ error ‘,’ success’ or ‘info’.

If you need to pass other props or properties, you can use alert_ Change status to such a function.

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 enumeration objects.

Split enumeration objects into separate files for reuse

The best feature about using enumeration objects for conditional rendering is reusability.

Back to the example case, alert component is usually reusable in react. Therefore, when you want to render it conditionally, you can also reuse it.

You can define the enumeration 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 a component.

import { ALERT_STATUS } from "./alertStatus"; 

The usage is the same as before.

6. Hoc conditional rendering

Best practices summary

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

~~

High order component (HOC) can be used to implement conditional rendering in react. You can use it when you want to run some logic or check before rendering components.

For example, you need to check that the user is authenticated before accessing certain components.

You can use hoc to protect those components instead of writing them in every component that needs authenticationif-elsesentence.

// 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 a component.

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

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

It’s better, isn’t it?

You can use hoc for other reusable conditional rendering, such asLoad indicator implementationNull checkAnd so on.

For more details about hoc (with functional components), you can visit the(https://medium.com/@albertchu539/higher-order-components-in-a-react-hooks-world-69fe1f0b0791)。

7. JSX conditional rendering with external library

Best practices summary

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

Although I don’t recommend this method, I just want you to know that there is a Babel plug-in that makes JSX have its own conditional rendering tag.

With 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 plug-in because it looks more readable for conditional rendering in JSX.

~~

Translator’s note: you can also implement a simple if component for simple judgment.

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

  return condition ? positive : negative;
}; 
< if condition = {isloggedin} then = {< hello / >} else = {< div > please log in first < / div >} / >

These are all seven methods you can use for conditional rendering in react.

Happy coding!

Translation fromhttps://dev.to/syakirurahman/react-conditional-rendering-best-practices-with-7-different-methods-16e3#6_Conditional_Rendering_with_HOC

Original author syakir Rahman

Blue autumn wind (GitHub / Hua 1995116)

last

If my article helps you, I hope you can help me. Welcome to my WeChat official account.Notes of autumn wind, replyFriendsYou can add wechat and join the communication group,Notes of autumn windWill always be with you.

Best practice of react conditional rendering (7 methods)

You can also scan the code and add my wechat friends to the communication group.

Best practice of react conditional rendering (7 methods)

Recommended Today

Rust and python: why rust can replace Python

In this guide, we compare the rust and python programming languages. We will discuss the applicable use cases in each case, review the advantages and disadvantages of using rust and python, and explain why rust might replace python. I will introduce the following: What is rust? What is Python? When to use rust When to […]