Home > Net >  How to dynamically import SVG from a web service and render it inline
How to dynamically import SVG from a web service and render it inline

Time:10-23

We have hundreds of SVG files that I am trying to render inline. I am using create-react-app which already has @svgr/webpack installed and configured. It allows me to add SVG inline like so:

import { ReactComponent as SvgImage } from '../Plans/Brownlow-Floor-Plan.svg';
...

<SvgImage style={{ width: "600px !important" }} />

enter image description here

enter image description here

Including SVG via an img tag make these kinds of things impossible: enter image description here

Any help will be greatly appreciated!

CodePudding user response:

There's an excellent package called react-svg that does exactly what you want.

You can use it with a simple src property that takes a url string, just like an <img> tag. But behind the scenes, it will download the svg file from the url and inject it inline. For example:

import { ReactSVG } from 'react-svg'

Component = () => <ReactSVG src="http://somewhere.com/my.svg" />,

CodePudding user response:

I am not sure if this will work for you but, you can try to using the tag <use /> within an <svg /> tag. For example:

<svg
    height={iconHeight}
    viewBox={`0 0 ${iconWidth} ${iconHeight}`}
    width={iconWidth}
>
    <use xlinkHref={`${svgPath}#${icon}`} />
</svg>

Where svgPath is the URL to the SVG, and icon is an ID set on the SVG. You can try to omit to the #${icon} portion.

Not sure if this helps though.

If you choose this route, you may be incompatible with IE... For that you can use svg4everybody, but tbh IE is dead and it should stay dead.

Cheers!

  • Related