I have a vite react project and I’m using MUI and typescript.
I’m trying to do dynamic icon import but it results in a type error. If I try without the string interpolation and provide a static string it works. However, there are like 2k icons and I would like to avoid a static mapping if possible…
Here’s my code:
import { useState, useEffect } from "react";
export default function DynamicIcon(props: { iconName: string }) {
const [IconComponent, setIconComponent] = useState<any>(null);
useEffect(() => {
const loadIcon = async () => {
if (props.iconName) {
try {
const { default: Icon } = await import(
`@mui/icons-material/${props.iconName}`
);
setIconComponent(<Icon />);
} catch (error) {
console.error("Failed to load icon:", error);
}
}
};
loadIcon();
}, [props.iconName]);
if (!IconComponent) {
return <div>Loading...</div>;
}
return <div>{IconComponent}</div>;
}