AI Workshop: learn to build apps with AI →
Patterns: React, how to dynamically choose a component to render

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


To render a list of menu items, each with its own icon, you can hardcode the icon component per item:

const menu = [
  {
    title: 'Home',
    icon: <HomeIcon className="mr-3 ml-1 h-5 w-5" /> 
  },
  { title: 'Notifications', icon: <BellIcon className="mr-3 ml-1 h-5 w-5" /> },
  { title: 'Profile', icon: <UserIcon className="mr-3 ml-1 h-5 w-5" /> },
]

(using @heroicons/react or similar). In the JSX you iterate over the menu and render {item.icon}.

If you need different props or classes per item (e.g. by breakpoint with react-responsive), storing a component reference or a string key is more flexible. One approach is to store the icon name as a string and map it to a component:

const menu = [
  { title: 'Home', icon: 'HomeIcon' },
  { title: 'Notifications', icon: 'BellIcon' },
  { title: 'Profile', icon: 'UserIcon' },
]

const Icon = (props) => {
  const { name } = props

  let icon = null
  if (name === 'HomeIcon') icon = HomeIcon
  if (name === 'BellIcon') icon = BellIcon
  if (name === 'UserIcon') icon = UserIcon

  return React.createElement(icon, { ...props })
}

...

<Icon name={item.icon} />

A cleaner approach is to use an object map instead of multiple if statements:

const icons = {
  HomeIcon,
  BellIcon,
  UserIcon,
}

const Icon = (props) => {
  const { name } = props

  const TheIcon = icons[name]
  return <TheIcon {...props} />
}

<Icon name={item.icon} />

The variable is named TheIcon (capitalized) because React treats uppercase names as components.

You can also pass the component directly in the menu array (no string mapping):

const menu = [
  { title: 'Home', icon: HomeIcon },
  { title: 'Notifications', icon: BellIcon },
  { title: 'Profile', icon: UserIcon },
]

const Icon = (props) => {
  const { icon } = props
  const TheIcon = icon
  return <TheIcon {...props} />
}

...

<Icon icon={item.icon} />

Lessons in this unit:

0: Introduction
1: React Concept: Composition
2: React Higher Order Components
3: React: Presentational vs Container Components
4: React Render Props
5: React Portals
6: Code Splitting in React
7: Server Side Rendering with React
8: React Concept: Purity
9: React StrictMode
10: Lifecycle events
11: ▶︎ React, how to dynamically choose a component to render