I’m trying to access a static image to use within an inline backgroundImage
property within React. Unfortunately, I’ve run up dry on how to do this.
Generally, I thought you just did as follows:
JavaScript
x
17
17
1
import Background from '../images/background_image.png';
2
3
var sectionStyle = {
4
width: "100%",
5
height: "400px",
6
backgroundImage: "url(" + { Background } + ")"
7
};
8
9
class Section extends Component {
10
render() {
11
return (
12
<section style={ sectionStyle }>
13
</section>
14
);
15
}
16
}
17
This works for <img>
tags. Can someone explain the difference between the two?
Example:
<img src={ Background } />
works just fine.
Thank you!
Advertisement
Answer
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:
JavaScript
1
2
1
backgroundImage: `url(${Background})`
2