Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Setting a backgroundImage With React Inline Styles

I'm attempting to get to a static picture to use inside an inline background picture property inside React. Sadly, I've run up dry on the best way to do this.

Usually, I thought you just did as follows:

import Background from '../images/background_image.png';

var sectionStyle = {
width: "100%",
height: "400px",
backgroundImage: "url(" + { Background } + ")"
};

class Section extends Component {
render() {
return (
<section style={ sectionStyle }>
</section>
);
}
}

This works for <img> tags. Can anyone describe the difference between the two?

Example:
<img src={ Background } /> works just fine.
by

2 Answers

rahul07
The curly braces inside backgroundImage property are wrong.

Probably you are using webpack along with image files loader, so Background should be already a String: backgroundImage: "url(" + Background + ")"

You can also use ES6 string templates as below to achieve the same effect:

backgroundImage: `url(${Background})`
pankajshivnani123
If you are using ES5 -

backgroundImage: "url(" + Background + ")"

If you are using ES6 -
backgroundImage: `url(${Background})`

Login / Signup to Answer the Question.