Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing SVG in React dynamically

Tags:

reactjs

svg

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?

like image 272
m_sultan Avatar asked Sep 13 '25 12:09

m_sultan


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 />
like image 159
lissettdm Avatar answered Sep 16 '25 03:09

lissettdm