Search code examples
javascriptreactjssvgreact-functional-component

How to load SVG from file/url and display as React component


I want to load an SVG from a file or through a URL and then use it as a React component.

I've tried many ways, but I can't figure out to do that correctly.

Can someone give me a hint to achieve it?

Currently I'm creating components this way, but as I mentioned, it should be at runtime loaded from a file instead:

const SvgComponent = (props) => (
  <svg
    height={800}
    width={800}
    xmlns="http://www.w3.org/2000/svg"
    viewBox="0 0 24 24"
    xmlSpace="preserve"
    {...props}
  >
    <path
      fill={props.color || '#000'}
      d="M23 24H3v-2h18V6.4L16.6 2H5v7H3V0h14.4L23 5.6z"
    />
    <path 
      fill={props.color || '#000'}
      d="M22 8h-7V2h2v4h5zM4.8 15.4l-3-4.4h2.3L6 13.9 7.9 11h2.3l-3 4.4 3.1 4.6H8l-2-3.1L4 20H1.7l3.1-4.6z" 
    />
  </svg>
)

Solution

  • For a URL, you'd just use the image tag <img src={svgUrl} ...>

    I suppose you could also fetch or read from file the SVG data as you would any other data and render it {svgData}.

    You can use FileReader's readAsDataURL and set the result to an image's src, or read the file (or fetch the data) an use <img src={URL.createObjectURL(photoData)} alt={photoName} /> or similar.