Search code examples
javascripthtmlreactjsinline-styles

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:

<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