fro
fro

Reputation: 477

Issue with displaying background image in a div with REACT

I am trying to display a background image in a div and though it works fine for a standard img tag I can't make it work for the div. What am I doing wrong? Below is where I import the image:

import imgPackage from '../img/package.png';

And below is the 2 pieces of code - div doesn't display anything and img works fine.

<div
  style={{
  height: '50px',
  width: '50px',
  backgroundImage: 'url(${ imgPackage })'
  }}
/>

<img src={imgPackage} alt="Smiley face" height="42" width="42" />

In the div backgroundImage I tried the following and none worked

backgroundImage: 'url(${ imgPackage })'
backgroundImage: 'url('+{ imgPackage }+')'
backgroundImage: 'url(../img/package.png)'

What am I doing wrong? Thanks!

Upvotes: 2

Views: 1495

Answers (3)

Kort
Kort

Reputation: 420

Any of your tries are wrong. Following variants will work after some changes:

If you prefer ES6 template literals you should use back-ticks quotes for them:

backgroundImage: `url(${ imgPackage })`;

If you prefer plain strings no need to add extra single quotes inside url():

backgroundImage: 'url( + { imgPackage } + )';

This case might working with appropriate url-loader from you webpack etc. Consider to use 2 examples above.

backgroundImage: 'url(../img/package.png)'

Upvotes: 1

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

Try using this. on single quotes you cant use ${} syntax. it can be used with `` back tick

backgroundImage: `url(${ imgPackage })`
backgroundImage: 'url('+ imgPackage +')'

Upvotes: 2

James Donnelly
James Donnelly

Reputation: 128856

You're trying to use a template literal but you're using single quotes instead of back-ticks.

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).

Template literals on MDN

<div
  style={{
    ...,
    backgroundImage: `url(${imgPackage})`
  }}
/>

Upvotes: 4

Related Questions