Kris Kris - 1 year ago 677
React JSX Question

Setting a backgroundImage With React Inline Styles

I'm trying to access a static image to use within an inline

property within React. Unfortunately, I've run up dry on how to do this.

Generally, 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 }>

This works for
tags. Can someone explain the difference between the the two?


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

Thank you!

Answer Source

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})`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download