Skip to content

React rendering

10 August 2022

Instead of a messy switch statement when conditionally rendering components, try an object instead.

jsx
const TAB = {
  HOME: 0,
  EXPLORE: 1,
  SETTINGS: 2,
};

function TabView({ activeTab }) {
  const tab = {
    [TAB.HOME]: <HomeTab />,
    [TAB.EXPLORE]: <ExploreTab />,
    [TAB.SETTINGS]: <SettingsTab />,
  };

  return tab[activeTab];
}

// Usage:

<TabView activeTab={2} />;