Matt Fuller
Matt Fuller

Reputation: 125

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...

Upvotes: 2

Views: 1435

Answers (3)

Areg Nikoghosyan
Areg Nikoghosyan

Reputation: 521

backgroundImage: `url(${Background})`

Upvotes: 0

Taouen
Taouen

Reputation: 65

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.

Upvotes: 0

Evren
Evren

Reputation: 4410

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.

Upvotes: 1

Related Questions