molkron
molkron

Reputation: 85

react inline style backgroundImage not shown

I am trying to load a background image in a react component. The image will ultimately vary so I am doing this with an inline style as follows:

const imageFilename = '../../../assets/img/picture.jpg';
<div className="auth-page" style={{backgroundImage: `url(${imageFilename}` , backgroundColor: '#cccccc'}}>

In chrome devtools I can see the style element which looks correct but no file is visible - I do see the background color though.

element.style {
    background-image: url(../../../assets/img/picture.jpg);
    background-color: rgb(204, 204, 204);
}

If I use a normal css file with background-image using the same path and filename the image is shown :

.auth-page {
  padding-top: 10vh;
  height: 100vh;
  background-image: url(../assets/img/full-screen-image-5.jpg);
  background-color: #cccccc;
}

Why does this not work using inline style (I remove background-image and background-color from the auth-page css style)?

Upvotes: 1

Views: 4423

Answers (3)

rahulfaujdar
rahulfaujdar

Reputation: 223

First Problem

Width and height have to be given along with the background image when the background image shows.

Second Problem

You are missing ) here: backgroundImage: url(${imageFilename}

Demo :-

    const imageFilename = ../../../assets/img/picture.jpg';
    <div className="auth-page" style={{backgroundImage: `url(${imageFilename})` , backgroundColor: '#cccccc', width: "100%", height: "100vh"}}></div>

Upvotes: 2

lissettdm
lissettdm

Reputation: 13078

Problem:

You are missing ) here: url(${imageFilename}

Try:

import Img from  '../../../assets/img/picture.jpg';

<div className="auth-page" style={{backgroundImage: `url(${Img})` , backgroundColor: '#cccccc'}}>

Upvotes: 3

Sean W
Sean W

Reputation: 6608

You need to import the image.

import imageFilename from '../../../assets/img/picture.jpg';

Upvotes: 1

Related Questions