Search code examples
reactjstypescriptsvgcreate-react-appinline

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


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

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:

  • http://myservice/api/getplan(100)
  • http://myservice/api/getplan(103)
  • http://myservice/api/getplan(106)
  • http://myservice/api/getplan(631)

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" />

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!


Solution

  • 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" />,