2

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!

1

3 Answers 3

4

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})`
  }}
/>
Sign up to request clarification or add additional context in comments.

Comments

2

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

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

Comments

1

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)'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.