Search code examples
javascriptreactjsdesign-patternscoding-stylerefactoring

Javascript (React.js) - Refactor a switch-case


I am creating a tab navigator which listen to my database and renders 5 different icons, one of them with a badge.

Currenlty, I am making this with a switch-case, to avoid returning the same component with different props 5 times. But the reallity is that it doesn't look really professional. Any design pattern to refactor this code?

      let iconName;
      let iconType = "material-community"; // app default icons from material-community
      let badgeNumber;

      switch (route.name) {
        case "Home":
          iconName = "home";
          break;

        case "Interactions":
          iconName = "heart";
          badgeNumber = props.notifications;
          break;

        case "Camera":
          iconName = "camera";
          break;

        case "Search":
          iconName = "search";
          iconType = "material";
          break;

        case "Profile":
          iconName = "person";
          iconType = "material";
          break;
      }

      return (
        <BadgedIcon
          number={badgeNumber} 
          name={iconName}
          type={iconType}
          color={color}
          size={24}
          badgeStyle={styles.interactionsBadge}
        />
      );

Solution

  • This how I would do it:

    const iconMap = {
      Home: {
        iconName: 'home',
        iconType: 'material',
        badgeNumber: props.notifcations
      },
      /// All your other route names:
    }
    
    return (
    <BadgedIcon
    number = { iconMap[router.name].badgeNumber }
    name = {iconMap[router.name].iconName}
    // All your other props: