Vadorequest
Vadorequest

Reputation: 17997

Style in SVG, not applied on the browser (React)

I'm trying to add a SVG into my webpage, I think the format is a bit odd.

https://gist.github.com/Vadorequest/c329dec26e39a586e96df5f74c1d7d29?short_path=d29c6c9 (you can see the source code and the rendering there)

The style part isn't correctly understood since I'm loading this file using React. If you save the file and open it in a browser, it'll work fine. But if I load it by react using react-svg-loader, it displays a dark image.

import IconBook from "-!react-svg-loader!../assets/couverture-eBook-VF.svg";
...
<IconBook height={250} />

Is it standard to put the style like this? Should I get a new SVG exported differently? I really don't know that format and all its possibilities.


Edit 1:

I found a working workaround for anyone interested: https://github.com/gilbarbara/react-inlinesvg

It basically loads the svg file over network and anything in it will be correctly loaded. (including <styles>)

On the bad side, it makes the app rely on something that must be available via CDN or alike. (you won't have the svg embedded in your app. If you wanted some kind of standalone app that can be built with everything in it, it's not really good)

On the good side, it doesn't require any change in the SVG file, you use it as it, load it over network, and it displays as in the browser.

Since I'm building a standalone app (basically, npm run build will generate a folder with my whole app) this isn't perfect because I need to host that file somewhere on a CDN. So I'll keep looking for another solution.

Upvotes: 0

Views: 1490

Answers (1)

Mario Nikolaus
Mario Nikolaus

Reputation: 2406

It is fine to have styles in your svg file, as specification says:

Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a document written in HTML or XML (including XML dialects such as SVG or XHTML). CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

https://developer.mozilla.org/en-US/docs/Web/CSS

Upvotes: 1

Related Questions