StochasticNerd StochasticNerd - 1 month ago 8
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

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>