React/Ionic: Not rendering SVG via <img/> tags

Viewed 504

I seem to be facing an issue with loading SVG's within my React/Ionic App. I am getting the weather via OpenWeatherMap and accessing which icon to use via this weather?.weather[0].icon I am using the following icon pack https://github.com/basmilius/weather-icons but when I insert the above it does not render the SVG icons I am using it like <img src={`../images/${weather?.weather[0].icon}.svg`}/> but it keeps showing it like the image is missing.

The images are in the images directory which has the same root directory as this page

Page is in src/pages
Image is in src/images  

Anyone have any tips on why this may be?

A sample SVG from the pack is:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><g><circle cx="32" cy="32" r="11.64" fill="#f4a71d"/><path fill="none" stroke="#f4a71d" stroke-linecap="round" stroke-miterlimit="10" stroke-width="3" d="M32 15.71V9.5M32 54.5v-6.21M43.52 20.48l4.39-4.39M16.09 47.91l4.39-4.39M20.48 20.48l-4.39-4.39M47.91 47.91l-4.39-4.39M15.71 32H9.5M54.5 32h-6.21"/><animateTransform attributeName="transform" dur="45s" from="0 32 32" repeatCount="indefinite" to="360 32 32" type="rotate"/></g></svg>
2 Answers

Problem

You need to change the way you are importing the images:

1. import an image from the same source directory:

import Img from "/path/to/image.svg"

<img src={Img}/>

2. import an image from the public folder:

<img src="/path/to/image.svg"/>

Solution:

If you want to import images dynamically and you are using Webpack, you can use require.context:

const svgDir = require.context("!@svgr/webpack!../images");

then:

<img src={svgDir(`./${weather?.weather[0].icon}.svg`)}/>

A quick tip on how to fix this can be found here --> https://css-tricks.com/forums/topic/svg-css-background-image-not-showing-in-chrome/

I believe the problem is with the SVG itself. If you open the SVG in the browser and inspect the code you will see the svg contains just a base64 encoded PNG http://staging.flagstaff.ab.ca/templates/base/images/page-bg.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1922" height="432" viewBox="0 0 1922 432">
  <image id="Swoosh" width="1922" height="432" xlink:href="data:img/png;base64,=====LONG BASE 64 ENCODE HERE=====" >
</svg>

Maybe some browsers/OS have problems in rendering the svg in this way.

Since it is not a real SVG just convert it in PNG and use the png instead. Or include the base64 directly in your css by changing

background-image: url('your-file.svg');
with

background-image: url('data:img/png;base64,=====LONG BASE 6

So...

xlink:href="data:img/png;base64,

to:

xlink:href="data:image/png;base64,

Check this response --> Chrome not rendering SVG referenced via <img> element

Related