Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
186
rated 0 times [  192] [ 6]  / answers: 1 / hits: 36713  / 7 Years ago, mon, august 21, 2017, 12:00:00

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!


More From » reactjs

 Answers
2

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>

[#56692] Friday, August 18, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
byronkodyo

Total Points: 552
Total Questions: 87
Total Answers: 104

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;