Reputation: 1295
I started looking into react today, and I have run into a problem. In my component's render function I have specified an array as follows, where the image attribute is a url to an image (Nattklunn is intended wrong spelling):
const songs = [{'title' : 'Nattklubb',
'author' : 'DigohD',
'image' : 'img/Nattklunn.png'},
{'title' : 'LED Beluga',
'author' : 'DigohD',
'image' : 'img/LED Beluga.png'},
{'title' : 'LED Elephantasia',
'author' : 'DigohD',
'image' : 'http://ovk.no/wp-content/uploads/2012/08/Husmus-Mus-Musculus.jpg'}]
Then I render them all using map and the following sub-functions:
function LBoxContent(props){
return <div className="lBoxContent" style={lContentStyle(props)}>
{songs[props.index].title}
<br />
{songs[props.index].author}
</div>
}
function lContentStyle(props){
return {backgroundImage: 'url(' + songs[props.index].image + ')'}
}
All the boxes are created and the title and author for each song are successfully pulled out of the array and listed correctly. However, the background image only works for the web url (third element in array) and not for my local urls. The local urls do work if I use them directly in the css file, however, So they are correctly pointing at the images.
So what am I missing? Are the local urls' format simply incorrect?
Thanks!
Upvotes: 2
Views: 10818
Reputation: 1
You may also use "require":
style={{backgroundImage: `url(${require(`${songs[props.index].image}`)})`}}
in this case you can use images addresses dinamically
Upvotes: 0
Reputation: 1548
If you are using create-react-app, you need to import the image using a Javascript module:
import nattklunn from './img/Nattklunn.png'; // import logo from '/img/Nattklunn.png'; if img is a folder at root.
[...]
const songs = [{'title' : 'Nattklubb',
'author' : 'DigohD',
'image' : nattklunn},
{'title' : 'LED Beluga',
'author' : 'DigohD',
'image' : nattklunn},
{'title' : 'LED Elephantasia',
'author' : 'DigohD',
'image' : nattklunn}
}]
Then:
function LBoxContent(props){
return <div className="lBoxContent" style={lContentStyle(props)}>
{songs[props.index].title}
<br />
{songs[props.index].author}
</div>
}
function lContentStyle(props){
return {backgroundImage: `url(${songs[props.index].image})`}
}
Upvotes: 11