Reputation: 31
First timer on stack overflow so I'll try my best.
I'm trying to dynamically add SVGs as background images for my buttons.
Created react app using create-react-app. I have 3~ files in question: poland.svg, Flag.jsx and exampleComponent.jsx
exampleComponent.jsx
import React from 'react';
import Flag from './Flag.jsx';
const exampleComponent = (props) => {
const backgroundImage = {
backgroundImage: `url(${Flag(props.nation)})`
}
return(
<button style={backgroundImage}>
<div />
</button>
)
}
export default exampleComponent;
Flag.jsx
import Poland from './poland.svg';
import US from './us.svg';
const Flag = (nation) => {
let path = "";
if (nation === "Poland") path = Poland;
else if (nation === "US") path = US;
return path;
}
export default Flag;
poland.svg
<svg
height="100%"
width="100%"
>
<defs />
<rect fill="#ffffff" width="100%" height="50%" />
<rect transform="translate(0, 50px)" fill="#ff0000" width="100%" height="50%" />
</svg>
I'm getting the file path /static/media/poland.49b43928.svg When I inspect the element in chrome the correct file path is shown but the SVG isn't being loaded!
IM STILL A NOOB! so please be harsh! ;D
Upvotes: 1
Views: 361
Reputation: 31
Update! So the file was being sent in XML format.. I wish I knew more to explain the details but all I did to fix this was add: xmlns="http://www.w3.org/2000/svg"
to the svg tags like so:
<svg
height="100%"
width="100%"
xmlns="http://www.w3.org/2000/svg"
>
<defs />
<rect fill="#ffffff" width="100%" height="50%" />
<rect transform="translate(0, 50px)" fill="#ff0000" width="100%" height="50%" />
</svg>
Upvotes: 1
Reputation: 413
If the svg files are similar, there may be a problem with matching the
<use xlink ID:href="#xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"/>,
where xxxxxxxx-xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx is the ID, it must be unique for each file.
See the link, it may help
https://github.com/SilverFox70/svg-react-loader
Upvotes: 0