Importing SVG in React dynamically

Viewed 3073

I'm trying to import SVG dynamically in my React Component

So instead of doing import { ReactComponent as LikeIcon } from '../../assets/svg/like.svg' everytime I need an svg I need to pass the name "like" for example to dynamically import it

I found a solution here: How to dynamically import SVG and render it inline

Which works great however when I build (npm run build) the svgs are not found

Any idea why?

1 Answers

If you are using Webpack, you can use require.context:

const svgDir = require.context('../../assets/svg/');

then:

<img src={svgDir(`./${filename}.svg`)}

As React Component:

const svgDir = require.context("!@svgr/webpack!../../assets/svg/");

const Icon = svgDir("./Group 9.svg").default

then:

<Icon />
Related