Reputation: 543
I need some assistance with the following problem. I'm using material ui icons, and the project is set in a way that when I want to use an icon I have to do this:
import {Muicon } from '@/lib/material';
...
<Muicon.Visibility />
With that the eye Icon appears.
Now what I want to do is this: there is an screen where the user could choose the Icon that want to show in other screen, so for example the user writes "Visibility" (just a string) and with that the <Muicon.Visibility /> component has to be showed in the other screen.
The problem is that I can't do something like
<Muicon.{userIcon} />
Can someone tell me how to do this? I have to create a component with the string that the user enters, there's a way to do this? or I need a different approach?
Thanks
Upvotes: 0
Views: 4447
Reputation: 21901
I would create a function to return the icon
const GenerateIcon = (variation, props = {}) => {
const IconName = Muicon[variation];
return <IconName {...props} />;
};
and use it
<div>
<p>{GenerateIcon("Visibility")}</p>
<p>{GenerateIcon("VisibilityOff")}</p>
<p>{GenerateIcon("AddAPhoto", {color: "secondary"})}</p>
</div>
here is a demo
If I want a more cleaner way to do this, I'll create a separate component
const Icon = ({ name, ...rest }) => {
const IconComponent = Muicon[name];
return IconComponent ? <IconComponent {...rest} /> : null;
};
and use it
<Icon name="Visibility" />
<Icon name="VisibilityOff" />
...
Upvotes: 6
Reputation: 980
You can do it like below
const SelectedIcon = Muicon[userIcon];
<SelectedIcon />
Upvotes: 3