Conditional rendering React: List of options and best practice for these patterns

When we’re developing a React application, we often need to show or hide an element given a certain situation. To clarify, in React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them. Be it a user interaction, the presence of data certainly coming from a request, or even permission levels. This module can be named as “Conditional rendering React” and it isn’t too difficult to perform as a result.

When a component has a conditional rendering, the appearance of the rendered component differs based on the condition. Also, in JSX – the syntax extension used for React – we have all the power of JavaScript, so, there are many options for conditional rendering React. So, in this article, we would like to show you guys these options in a definitive way, and some best practices for these patterns.

The most basic conditional rendering logic in React is done with a single if statement instead. For instance, a List component in React shouldn’t render the list HTML elements in a view if there is no list of items in the first place. You can use a plain JavaScript if statement to return earlier: Let’s look at the example below.

 const users = [
  { id: '1', firstName: 'Robin', lastName: 'Wieruch' },
  { id: '2', firstName: 'Dennis', lastName: 'Wieruch' },
];
function App() {
  return (
    <div>
      <h1>Hello Conditional Rendering</h1>
      <List list={users} />
    </div>
  );
}

function List({ list }) {
  if (!list) {
    return null;
  }
  return (
    <ul>
      {list.map(item => (
        <Item key={item.id} item={item} />
      ))}
    </ul>
  );
}

function Item({ item }) {
  return (
    <li>
      {item.firstName} {item.lastName}
    </li>
  );

#2. If else

So, let’s move on with the previous example to learn about “if else” statements in conditional rendering React. If there is no list, we render nothing and hide the HTML as we have seen before with the single if statement. However, you may want to show a text as feedback for your user when the list is empty for better user experience.

 function List({ list }) {
  if (!list) {
    return nu
  }

  if (!list.length) {
    return <p>Sorry, the list is empty.</p>;
  } else {
    return (
      <div>
        {list.map(item => (
          <Item item={item} />
        ))}
      </div>
    );
  }
}

#3. Ternary

Another way to express a definitive if else statement for conditional rendering React in JavaScript is the ternary operator. For instance, imagine your component shows either a preview or edit mode. The condition is certainly a JavaScript boolean which comes in as React prop. As a result, you can use the boolean to decide which element you want to conditionally render here.

#4. Conditional Rendering React: switch case

Now, there might be cases when you have multiple conditional renderings. As a result, you can use a switch case operator for multiple conditional rendering React. It’s wise to use the default for the switch case operator because a React component always has to return an element or null. If a component has a conditional rendering based on a string, it still makes sense to describe the interface of the component with TypeScript. So, let’s take a look at the example:

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

#5. &&

It happens often that you want to render either an element or nothing. You have also learned that a simple if condition helps with that issue. However, then again you want to be able to inline the conditional rendering React like a ternary operator. Take the following loading indicator component which uses a conditional ternary operator to return either the element or nothing:

 function LoadingIndicator({ isLoading }) {
  return <div>{isLoading ? <p>Loading...</p> : null}</div>;
}

This certainly works just fine and you are done inlining the condition in your JSX. However, there exists an alternative way that omits the necessity to return null. Therefore, the logical && operator helps you to make conditions that would return null more concise. As a result, in React, you can make use of this behavior. If the condition is true, then the expression after the logical && operator will be the output. If the condition is false, React subsequently ignores and skips the expression.

#6. HOC when using conditional rendering React

Higher-order components are obviously the perfect match for this. To clarify, this module can help with multiple use cases, yet one use case could be to alter the look of a component with a conditional rendering. A HOC can also hide away all the noise from your actual component. Ultimately, you could add multiple higher-order components (composition) to hide away more than one conditional rendering React edge case. Let’s check out a HOC that either shows an element or a component:

 // Higher-Order Component
function withLoadingIndicator(Component) {
  return function EnhancedComponent({ isLoading, ...props }) {
    if (!isLoading) {
      return <Component {...props} />;
    }
    return (
      <div>
        <p>Loading</p>
      </div>
    );
  };
}
const ListWithLoadingIndicator = withLoadingIndicator(List);
function App({ list, isLoading }) {
  return (
    <div>
      <h1>Hello Conditional Rendering</h1>
      <ListWithLoadingIndicator isLoading={isLoading} list={list} />
    </div>
  );
}

Final words

To conclude, here are some of the best options for Conditional rendering React and the best practice for these patterns. All of the above approaches are valid when used in the right context, it is up to us to use the superpower called “Good Sense” to use each one in the appropriate situation. When you choose them wisely, your website will become much better, while sales and conversions increased. If have any questions, don’t hestitate to contact to our React JS development services.


Tags

Share