I'm trying to display two svg images to my page in react but it doesn't work, do you know why?
Here's the manifest.json file:
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "stone_black.svg",
"sizes": "64x64",
"type": "image/svg+xml"
},
{
"src": "stone_white.svg",
"sizes": "64x64",
"type": "image/svg+xml"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
And here's where I implement it:
function Square(props) {
// Elements that will display the game stones
var srcToDisplay = ""
if (props.value === "white") {
srcToDisplay = "public/stone_white.svg"
} else if (props.value === "black") {
srcToDisplay = "public/stone_black.svg"
} else {
srcToDisplay = ""
}
return (
<button
className="squares"
onClick={props.onClick}>
<img src={srcToDisplay} />
</button>
)
}
Thanks a lot in advance :)
When using images in React, the general rule is to import the images into your component. I don't know the specifics of your setup, but if you're using most standard setups for React you should use something like this:
import stone_white from 'public/stone_white.svg'; // The relative path to the image
import stone_black from 'public/stone_black.svg';
function Square(props) {
// Elements that will display the game stones
if (props.value === "white") {
srcToDisplay = stone_white;
} else if (props.value === "black") {
srcToDisplay = stone_black;
} else {
srcToDisplay = ""
}
return (
<button
className="squares"
onClick={props.onClick}>
<img src={srcToDisplay} />
</button>
)
}
Also, you probably don't want to be getting the images from the public
directory. You might want to think about storing images in a dedicated directory in your src
folder.