Reputation: 285
I'm trying to dynamically use the item's id while mapping through my items array in my Render(). How can I do this from within the render mapping I already have?
render() {
return (
<div className="container">
<h1>New Houte</h1>
{this.state.items.map(item =>
<div className="item-container" key={item.id}>
<div style={ { backgroundImage: 'url("../../images/' +{item.id} + ')' } } className="image-container" key="image">
Upvotes: 1
Views: 215
Reputation: 21
Another way of doing is to use template literals.
In your case, it would be like this using backtick(the key left of number 1)
`{ { backgroundImage: `url("../../images/${item.id}")` } }`.
Upvotes: 1
Reputation: 5960
Don't do:
<div style={ { backgroundImage: 'url("../../images/' +{item.id} + ')' } } className="image-container" key="image">
But do:
<div style={ { backgroundImage: 'url("../../images/' + item.id + '")' } } className="image-container" key="image">
or:
<div style={ { backgroundImage: `url("../../images/${item.id}")` } } className="image-container" key="image">
You open braces {} inside JSX to evaluate. Here, you're just inside a string, so it's raw JS and that's why it doesn't work :)
Upvotes: 1