Dynamic imports of Material UI Icons

What if we can't hardcode which icon to use in our react component and the icon to use is specified in a CMS or a JSON source?

Typically when we build sites with Material UI's icons, we just import the icon to use directly and insert it into our react component.

import { Add } from '@material-ui/icons'

export default () => (
  <div>
    // component content...
    <Add />
  </div>
)

This approach is fine as long as the icon to use is known ahead of time. But what if the icon to use is specified by a CMS or a JSON file? Let's say we are just given the name of the icon we want to display: "Add"

We can solve this by importing the icons and then picking the specified icon by its name:

import * as MuiIcons from '@material-ui/icons'

export default ({ iconName }) => (
  <div>
    // component content
    {MuiIcons[iconName]}
  </div>
)

With this approach we are able to display arbitrary icons from Material UI dynamically:

<ComponentWithIcon iconName="Add" />
<ComponentWithIcon iconName="Anchor" />
<ComponentWithIcon iconName="Assignment" />