StochasticNerd StochasticNerd - 1 year ago 66
Javascript Question

Rendering style elements inside React components

I'm trying to render the following line of code in React.

<div className="img" style={{background-image: url(image.src)}}></div>

I'm getting a litany of parsing error. Would really appreciate some help in getting the correct React'ive' syntax on this one.

Answer Source

background-image needs to be backgroundImage and then you need to do string interpolation on the url {{backgroundImage: `url(${image.src})`}}

otherwise when it is parsed how you have it now, react will think url is a function and attempt to call it with image.src.

this would also work

var image = "url(" + image.src + ")";
var style = {backgroundImage: image};
<div className="img" style={style}></div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download