I'm trying to fetch SVG images dynamically in my react component, but so far I'm getting this error Uncaught (in promise) TypeError: Failed to fetch dynamically imported module. This is my code sample
import React from 'react';
import { CustomSvgIcon } from '../../util/CustomSvgIcon';
const Icon = ({ iconName }: IconProps) => {
const [menuIcon, setIcon] = React.useState<string | null>(null);
React.useEffect(() => {
if (iconName) {
import(`../../../assets/svg/${iconName}.svg`)
.then((bla) => setIcon(bla.default))
.catch((error) => console.log(error));
}
}, []);
return (
<CustomSvgIcon>
{menuIcon ? menuIcon : null}
</CustomSvgIcon>
);
};
This code works perfectly in the storybook, but when I use it in the react component it won't load images and that error pops. What am I doing wrong?
This issue is solved with setting some rules in webpack.config. It was issue with .svg
. This is the rule that solved the issue:
{
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
icon: true,
},
},
],
}