4

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?

m_sultan
  • 433
  • 5
  • 14

1 Answers1

9

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 />
lissettdm
  • 12,267
  • 1
  • 18
  • 39
  • thank you your answer led me to this: https://stackoverflow.com/questions/45754739/how-to-import-an-entire-folder-of-svg-images-or-how-to-load-them-dynamically-i I used the second answer if anyone has the same problem and reads this – m_sultan Mar 04 '21 at 13:36
  • Yes, if you want to use it as react component then const svgDir = require.context("!@svgr/webpack!../../assets/svg/"); and const Icon = svgDir("./Group 9.svg").default – lissettdm Mar 04 '21 at 13:38