BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11663

set background image through function or variable

I'm trying to change the background image of a div depending on various circumstances in a React component but first I need to figure out if it's possible to set the background image through a variable or a function, and it doesn't seem possible. For example, with a variable, something like this pseudo code doesn't seem to work

render: function(){
var myvariable = "url('http://localhost:8080/assets/myimage.jpg')"
return (
    <div style={{ "backgroundImage": { myvariable }, "width": "300px"}}</div>
     )
}

I also tried to call a function from the inline styles, but the compiler objected toe . in this.setBackgroundImage

 setBackgroundImage: function(){
     return "url('http://localhost:8080/assets/myimage.jpg')"
 },
 render: function(){

    return (
        <div style={{ "backgroundImage": { this.setBackgroundImage }, "width": "300px"}}</div>
         )
    }

Question: is it possible to call a function or use a variable in inline styles in React and, if not, how could I achieve what I'm attempting to do (i.e. rotate background images for a div)?

Note, the div has to have other styles on it (width, height etc), not just the background image

Upvotes: 3

Views: 9108

Answers (1)

Dmitry Zaets
Dmitry Zaets

Reputation: 3277

Basically what you need to do is to compose styles like:

var divStyle = {
  backgroundImage: 'url(' + imgUrl + ')',
  width: '300px'
};

And then use them inline:

return (
  <div style={divStyle}></div>
)

React Inline Styles

Upvotes: 5

Related Questions