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" }} />
Similar question provides a solution for dynamically rendering SVG inline. However, In my case, I don't have any SVG files in the source code. Instead, all SVG files are returned to me via a call to an API service. For example:
As a result, by the time webpack is run, it has no information about these SVG files.
So my question is: is it possible to render svg dynamically in react (TypeScript) if I pull SVG file from an external URL?
This is not a duplicate question: How to dynamically import SVG and render it inline
Approach described in the question above is not going to work because it expects all SVG files to be added to the source code.
This approach also not going to work because simply using an img tag will not pull SVG inline:
<img src="plan.svg" />
Including SVG via an img tag make these kinds of things impossible:
Any help will be greatly appreciated!
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" />,