0

I need to dynamically insert some Material UI icons into my code based on some string found in a configuration file. I found a technique that should work here: https://medium.com/@Carmichaelize/dynamic-tag-names-in-react-and-jsx-17e366a684e9

However, when I tried it for React Functional Components + Typescript I get weird errors:

enter image description here

How would I achieve this using Typescript? The types really throws me off.

Essentially, I would like to use this component like such:

<ListItemIcon>
    <SideNavIcon name='dashboard' />
</ListItemIcon>
<ListItemIcon>
    <SideNavIcon name='transform' />
</ListItemIcon>
Mark
  • 2,137
  • 4
  • 27
  • 42

1 Answers1

1

Would it be acceptable create a separate function with a switch-case that switches on the "name", and returns the correct IconComponent for each case? Then just return that function in your SideNavIcon component?

Should be fine if you are OK with hard-coding what icons should be available.

If you need a completely dynamic solution, i would look at dynamic component loading, which is discussed here (among other places) React / JSX Dynamic Component Name

Magnus Ingwersen
  • 374
  • 3
  • 11