'how do I set a background image on div in react js?
I'm trying to set a background image that changes per card element. The website is a recipebook, basically I just want each individual card to be the image of the recipe.
import React from "react";
import "./card.css"
const Card = ({recipe}) => {
return (
<div className="card-bg tc dib br3 pa3 ma2 grow bw2 shadow-5" style={{backgroundImage: `url("${recipe.img}")` }}>
<p className="test">{recipe.name}</p>
<p className="desc">
Recipe type: {recipe.type}
</p>
<p className="desc">
Author: {recipe.author}
</p>
<a href="{recipe.link}"><p className="desc">Recipe Link</p></a>
<hr />
</div>
);
};
export default Card;
I'm not getting any errors from this, but nothing is changing in the background. What am I doing wrong?
fyi, the image path is located in the json file as per below, per recipe:
{
"id": 1,
"name": "Carrot cake",
"type": "sweet",
"author": "Grandma",
"link": "recipes/carrotcake.html",
"img" : "../img/carrot.jpg"
},
Thanks in advance!
EDIT: The background property is showing in chrome devtools on inspection, it just isn't visible.
EDIT:EDIT: I've discovered that I can move the IMG folder anywhere in the project and not change the image path, and despite this, chrome developer tools still shows the background property on the DIV at the original path, yet doesnt throw an error...
Solution 1:[1]
Seems like you made mistake in style={{backgroungImage: url("${recipe.img}")
Change g with d. If it does not fix and you are using API to get the image, I would recommend you to check API to see image part.
Solution 2:[2]
Try moving the img folder into the public folder of the react app, and change the file path to '/img/carrot.jpg'.
I had this same issue a while back, and I think this is what fixed it.
Solution 3:[3]
backgroundImage: `url(${Background})`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Evren |
| Solution 2 | Taouen |
| Solution 3 | Areg Nikoghosyan |
