Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting inline backgroundImage is not working in React

I am using a function which will return the full path of the image.

  const imagePath = (imagePath) => {
    const domainPath = "http://localhost:9005/gallery/original/";
    const fullImagePath = domainPath + imagePath;
    return fullImagePath;
  };

Now If I use below code, it will work and show image on browser:

<img
 src={imagePath(item.mediaPath)}
 alt="cow images"
/>

But If I use below code, it will NOT work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div
  className="bg-image-blur"
  style={{
    backgroundImage:
      "url(" +
      imagePath(item.mediaPath) +
      ")",
  }}
></div>

Please see given below image from my inspect element. Style is added to the element :
enter image description here

and It will also not work if I don’t use imagePath function :

<div
  className="bg-image-blur"
  style={{
    backgroundImage:
      "url(" +
      "http://localhost:9005/gallery/original/" +
      id.mediaPath +
      ")",
  }}
></div>

What is the issue ?

>Solution :

It does not work because you haven’t put '' for url. And I’d suggest you use template literals for your string concat instead for easier look

<div
  className="bg-image-blur"
  style={{
    backgroundImage: `url('${imagePath(item.mediaPath)}')`,
  }}
></div>

You can check this document to understand how background-image looks like with url

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading