简体   繁体   中英

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!

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})`
  }}
/>

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM