How do you use React collection attributes in inline styling?

I'm attempting to set the background image for each item in a collection but I'm receiving a syntax error when attempting to access the model attribute. Can anyone help out?

You can assume the collection has been received.

class MyThing extends React.Component {

  const collection = this.props.collection;

  render () {
    return (
      <div> 
        {collection.models.toList().map((model,key) =>
        <div className="post" key={model.id}>
          <div className="graphic" 
             style={{background:"url(" + {model.img_url} + ")"}}>
          </div>
        </div>
        )}
      </div>
    );
  }
}

However, I'm receiving the following syntax error which implies I can't use the normal dot notation to access the attribute:

ERROR in ./MyThing.js
Module build failed: SyntaxError: Unexpected token, expected , (55:87)

  53 | div className="post" key={model.id}>
> 55 | <div className="graphic" style={{background:"url(" + {model.img_url} + ")"}}></div>
     |                                                            ^

What's the appropriate way of setting model attributes from a collection like this?

Any thoughts?

1 answer

  • answered 2018-02-13 02:14 Vincent D'amour

    Try removing the curly brackets around model.img_url to get this:

    <div className="graphic" style={{background:"url(" + model.img_url + ")"}}></div>