Better Conditional Rendering in React with Many Conditions

Better Conditional Rendering in React with Many Conditions

Conditional rendering is a powerful tool in React that allows you to render different content based on certain conditions. However, when you have many conditions to check, it can be easy to end up with a messy and difficult-to-maintain codebase.🤯

Messy example:

import PremiumView from "./PremiumView";
import ProView from "./ProView";
import FreeView from "./FreeView";
import BasicView from "./BasicView";
import DefaultView from "./DefaultView";


function MyComponent({ user }) {
   return (
    <div className="zhioua">
      {user.plan === "premium" ? (
        <PremiumView />
      ) : user.plan === "pro" ? (
        <ProView />
      ) : user.plan === "free" ? (
        <FreeView />
      ) : user.plan === "basic" ? (
        <BasicView />
      ) : (
        <DefaultView />
      )}
    </div>
  );
}

export default MyComponent;

This example uses a nested if/else statement to render the appropriate view based on the user's plan. This approach is messy and difficult to maintain, especially if you have a large number of plan options.

One way to improve your conditional rendering code is to use an object to map the conditions to the corresponding components. This is more efficient and scalable than using a series of if-else statements or ternary operators...🤓( you can use the Switch too )

Better example:

import PremiumView from "./PremiumView";
import ProView from "./ProView";
import FreeView from "./FreeView";
import BasicView from "./BasicView";
import DefaultView from "./DefaultView";

const planViews = {
premium: PremiumView ,
pro: ProView ,
free: FreeView ,
basic: BasicView ,
};

function MyComponent({ user }) {
  // Correct way: Using the planViews object to render the appropriate view
  const CurrentView = planViews[user.plan] ?? DefaultView;
  return (
    <div className="zhioua">
      <CurrentView />
    </div>
);
}

export default MyComponent;

This example uses the planViews object to render the appropriate view based on the user's plan. This approach is much simpler and easier to maintain than the nested if/else statement approach.

Conclusion:

I recommend using the simple example code, as it is more readable, maintainable, and scalable.

Let's connect: