Home > front end >  Dynamic background image for reusable components using inline style
Dynamic background image for reusable components using inline style

Time:04-03

I have an assets.js file that I use to handle images and videos like this.

import Bag from "./Bag.png";
import World from "./World.png";

export default {
  World,
  Bag,
};

I also have a parent component let's call A. The component renders a sub-component let's call B twice. Each time with a different background image and different text. My initial approach was to create an object like this

import assets from "../../assets/assets";

const category = [
  {
    type: "For Domestic",
    bgImage: assets.Bag,
  },
  {
    type: "For International",
    bgImage: assets.World,
  },
];

This object is what I would pass to the child component as props like

<B  category={category[0]} />
<B  category={category[1]} />

Now in the child component B, this was my initial approach

const Trips = ({category }) => {
return(
  <div
      className="Trips__container flex__container-v"
      style={{
        backgroundColor: theme.tripsColor,
        backroundImage : category.bgImage,
      }}
    >
    </div>
)
}

I did import everything correctly and passed down the components correctly. However, my images don't show up as the background. What am I doing wrong? Background colors work well and also other inline CSS works. I don't get what is different for background images.

Any other suggestions or a different approach are welcome.

CodePudding user response:

Try adding background Images like this:

backroundImage : 'url(' category.bgImage ')'

CodePudding user response:

You may need to pass image like this

 `url(${category.bgImage})`
  • Related