Home > OS >  Why background-Image not getting applied using inline styles?
Why background-Image not getting applied using inline styles?

Time:05-17

I have a Hero component in react.js :

 if(item.fields!=undefined)
  {
    var img1=item.fields.images[0].fields.file.url
  return (
    <Hero hero="roomshero" style={{backgroundImage:`${img1}`}}>
      <Banner className="banner" title={`${item.fields.name}`} subtitle="none">
        <Link to="/rooms" className="btn-primary">Back to Rooms</Link>
      </Banner>
    </Hero>
  )}

I am getting matching the item clicked by the user and after searching it my data.js file, setting the appropriate item. Each item has a unique image and hence has to be rendered dynamically. But this is not working in my case.

CodePudding user response:

You have to add url infront of your given img1 url . Example :

 if(item.fields!=undefined)
 {
    var img1=item.fields.images[0].fields.file.url
    return (
        <Hero hero="roomshero" style={{backgroundImage:`url(${img1})`}}>
            <Banner className="banner" title={`${item.fields.name}`} subtitle="none">
                 <Link to="/rooms" className="btn-primary">Back to Rooms</Link>
            </Banner>
         </Hero>
  )}

Also don't forget to set the width and height properties to banner tag to view the image.

CodePudding user response:

You have to use the url() CSS function there.

<Hero hero="roomshero" style={{backgroundImage:`url(${img1})`}}>
     ...
</Hero>

Hope this would be helpful.

  • Related