1. Home
  2. React
  3. Six methods to achieve conditional rendering in React

Conditional Rendering in React

Shuvo Habib

Shuvo Habib

Storyteller about JavaScript, new Frontend dev technologies, and A/B testing

Last updated on

Table of Contents

What is Conditional Rendering?

While developing an application in React or any other JS library/ framework, it is a common use case to show or hide elements based on certain conditions. It can be a simple user interaction – say, we need to show a popup when a user clicks a certain button and hide it when (s)he clicks the cross icon. To quote another example, think authentication – we make a ‘log out’ button visible when (s)he is logged in and make ‘Login/Sign up’ form visible for the opposite situation. This process of executing logic or rendering UI elements basis certain conditions is called conditional rendering.

In this article, we’ll be discussing conditional rendering in ReactJS and looking at different ways to handle those cases. We cover below the most useful methods for conditional rendering in react:

  • if/else
  • Ternary operation
  • Inline IF with Logical && operator
  • Switch case operator
  • Conditional Rendering with enums
  • Higher-Order Components
Conditional_Rendering-10_16X9-1180x664-w1dkp

if/else

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, and let React update the UI to match them. We use an if with our condition and return the element to be rendered.

Let’s observe the example below.

Consider these two components:

LoggedInUser Component:

function LoggedInUser(props) {
  return <div>
     <h1>Welcome back! </h1>
     <span>Log out </span>
   </div>;
}

LoggedOutUser Component:

function LoggedOutUser(props) {
  return <div>
     <h1>Sign in, please! </h1>
     <span>Log out </span>
   </div>;
}

We’ll create a LoggedStatus component that displays either of these components depending on whether a user is logged in or not. A different greeting is rendered depending on the value of isLoggedInprop.

function LoggedStatus(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <LoggedInUser />;
  }
return <LoggedOutUser />;
}
ReactDOM.render(
  <LoggedStatus isLoggedIn={false} />,
  document.getElementById('root')
);

Ternary operation

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

condition ? “This is True” : “This is False”

When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”.

How can we use this in React JS?

Consider this use case – Show an “Update” button when an edit has been made, else, show the “Edit” button.

render() {
  const edited = true;
  return (
    <div>
      {edited ? (
        <UpdateButton onClick={this.handleUpdateClick} />
      ) : (
        <EditButton onClick={this.handleEditClick} />
      )}
    </div>
  );
}

In the above example, when “edited” is true, we’ll show the “Update” button to the user. If “edited” is false, the “Edit” button is rendered.

Inline If with Logical && Operator

&& is a boolean operator, which essentially means “and”. For the condition to evaluate to true, both of the statements must be individually true.

Below is an interesting example. Let’s say we want to render a message saying “You have X tasks to do”. When there are no pending tasks, no message should be displayed.

function TodoComponent(props) {
  const todoList = props.todoList;
  return (
    <div>
      <h1>Hi User!</h1>
      {todoList.length > 0 &&
        <h2>
          You have {todoList.length} Tasks to do.
        </h2>
      }
    </div>
  );
}
const todo = ['Eat', 'Play', 'Read'];
ReactDOM.render(
  <Task todoList={todo} />,
  document.getElementById('root')
);

Observe carefully – When the length of the array is 3 (which is > 0), we’ll print, “You have 3 Tasks to do.” If the length is 0, we print nothing.

Switch Case operator in React

Interestingly, we can write switch case inline just like normal Javascript for conditional rendering in React. However, you would need a self-invoking JavaScript function. Take a look at the implementation below.

function Notification({ param }) {
  return (
    <div>
      {(function() {
        switch(param) {
         case 'foo':
          return 'bar';
         default:
          return 'foo';
         }
        }
      })()}
    </div>
  );
}

Note carefully though that you always have to use default for the switch case operator since in React, a component always needs to return an element or null.

To make it cleaner, we can get the switch out of the render in a function and just call it passing the params we want. See the example below.

renderSwitch(param) {
  switch(param) {
    case 'foo':
      return 'bar';
    default:
      return 'foo';
  }
}
render() {
  return (
    <div>
      {this.renderSwitch(param)}
    <div>
  );
}

In a nutshell, the switch case operator helps us to have multiple conditional renderings. That’s great!

Hold on, but this may not be the best way to achieve multiple renderings. Conditional renderings with enums is much more neat and readable compared to the switch case operator. Let’s then see how we can have multiple conditional renderings with enums.

Conditional Rendering with enums

In JavaScript, an object can be used as an enum when it is used as a map of key-value pairs.

const ENUMOBJECT = {
  a: '1',
  b: '2',
  c: '3',
};

Let’s look at an example. We want to create three different components Foo, Bar and Default. We want to show these components based on a certain state.

const Foo = () => {
  return <button>FOO</button>;
};
const Bar = () => {
  return <button>BAR</button>;
};
const Default = () => {
  return <button>DEFAULT</button>;
};

We’ll now be creating an object that can be used as an enum.

const ENUM_STATES = {
  foo: <Foo />,
  bar: <Bar />,
  default: <Default />
};

Let’s now create a function that will take state as a parameter and return components based on “state”. The “EnumState” function below is quite self-explanatory.

function EnumState({ state }) {
  return <div>{ENUM_STATES[state]}</div>;
}

The state property key above helps us to retrieve the value from the object. You can see that it is much more readable compared to the switch case operator.

Let’s create an Enum component, which will pass the values of “state” to the function “EnumState”.

class Enum extends React.Component {
  render() {
    return (
      <div>
        <h1>Conditional Rendering with enums</h1>
        <EnumState state="default"></EnumState>
        <EnumState state="bar"></EnumState>
        <EnumState state="foo"></EnumState>
      </div>
    );
  }
}
ReactDOM.render(<Enum />, document.getElementById("app"));

That’s it! We have conditional rendering implemented smoothly with enums. For the full example, check out this Codepen link.

As we saw, the enum approach is more readable in comparison to the switch case statement. Objects as enum open up a plethora of options to have multiple conditional renderings.

Higher Order Components

Higher order components or HOCs are often considered a difficult pattern to grasp in ReactJS. HOCs can be used for multiple use cases, however in this article, we’ll be picking up HOC for conditional rendering.

HOCs are a perfect match for conditional rendering in React and can have several use cases. One of them can be to alter the look of a component. To make it more specific, it can be used to conditionally render the component itself.

Let’s now take a look at a HOC that either shows a loading indicator or the desired component.

// HOC declaration
function withLoading(Component) {
  return function EnhancedComponent({ isLoading, ...props }) {
    if (!isLoading) {
      return <Component { ...props } />;
    }
    return <div><p>Loading...</p></div>;
  };
}
// Usage
const ListWithLoading= withLoading(List);
<ListWithLoading
  isLoading={props.isLoading}
  list={props.list}
/>

In the above example, the List component can focus on rendering the list. It doesn’t have to bother about a loading state. Ultimately, we could add more HOCs to shield away multiple conditional rendering edge cases.

Conclusion

In summary, we saw multiple ways to achieve conditional rendering in React. Each approach has its own advantages and some, like the enum approach can help you achieve more readable code than others. Simplicity, though, is also an important consideration when using any of these approaches – all your use case may need is just the if operator. In effect, pick the approach that best fits your use case at hand and hope we simplified your decision making a bit through this article 🙂

// Related Blogs

// Find jobs by category

You've got the vision, we help you create the best squad. Pick from our highly skilled lineup of the best independent engineers in the world.

Copyright @2024 Flexiple Inc