9

I am trying to set a background image via inline styles in React.

After looking through a few posts this one's solution worked for me:

<div className="phase1" style ={ { backgroundImage: "url('https://lh3.googleusercontent.com/MOf9Kxxkj7GvyZlTZOnUzuYv0JAweEhlxJX6gslQvbvlhLK5_bSTK6duxY2xfbBsj43H=w300')" } }>

I pasted that directly into my component without changing the link just to test it, and it worked. But now that I am trying to reference an image from my /src folder it isn't working.

<div className='background-image' style ={ { backgroundImage: "url('../../../../images/products/cards/main.jpg')" } }>asdfasdfasdfasdf</div>

Nothing shows up and I am not getting any error or warning.

Any help would be really appreciated!

Gage Hendy Ya Boy
  • 1,456
  • 4
  • 17
  • 35
  • Check this link - https://stackoverflow.com/questions/39195687/setting-a-backgroundimage-with-react-inline-styles – koolkat Aug 21 '17 at 23:57

4 Answers4

15

I figured it out, you can't just put a link straight into url. You need to require it first.

var bg=require('../../../../images/products/cards/main.jpg')
return (      
  <div className="ProductItem">

      {/* Background Image */}
      <div className='background-image' style ={ { backgroundImage: "url("+bg+")" } }></div>
Gage Hendy Ya Boy
  • 1,456
  • 4
  • 17
  • 35
  • 1
    That's not necessary, you just need to ensure that the image you're trying to load is in a public path (If you access that path with your browser the image is visible) – Miguel Aug 22 '17 at 00:03
  • @Miguel sometimes the image you need to load is not in a publica path and you can't ensure it will be – user3808307 Oct 17 '19 at 09:49
6

Hello

Everybody after some Research I found a better solution for this question like this

import BannerBgImg1 from "../../assets/static/img/banner/banner_bg_img_1.jpg";

<div className="bannerInnerItem" style={{backgroundImage: `url(${BannerBgImg1})` }}>

is the best way to use this

Masud Rana
  • 590
  • 1
  • 8
  • 17
1
 const Images = [
    require('./greenbanner.jpg'),
    require('./greengrass.jpeg'),
    require('./opengreen.jpg')   ];

This is for an array of images that should be required
we need to require them when they cannot be loaded

Klod Lala
  • 153
  • 8
1

I hope Background Img is very common. So please try to use it. It is very easy to use. At first you should import img and then easily use it in your jxs file.

import InnerBgImg from "../../assets/static/img/banner/inner_banner_bg_static.jpg";
return (
    <div className="inner_banner" style={{ backgroundImage: "url(" + InnerBgImg +")" }}>
Masud Rana
  • 590
  • 1
  • 8
  • 17