Reputation:
How to call/display the icons based on the array data code?
data = [{
img: '01d'
}, {
img: '02d'
}]
data && data.map((item) => (
<img src={`./icons/${item['img']}.svg`} />
))
What I'm trying to do here is to display the icon based on the img code
dynamically.
QUESTION 2
after adding the require()
, how to fix the You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Upvotes: 1
Views: 604
Reputation: 2247
Your error is here:
data && data.map((item) => (
<img src={`./icons/${data['img']}.svg`} /> // Error: data['img']
))
Explainaiton:
data is an array of objects. To access the first element you need to access with either data[0]['img'].
But since you have already created a map, you can use the item
to access the object. So you can now use item['img']
instead.
data && data.map((item) => (
<img src={`./icons/${item['img']}.svg`} />. // replace data by item as it contains the object on every iteration
))
UPDATE: As per you 404 error comment,
The path you provided is not correct. Try this:
Assuming your path is: ProjectFolder/src/icons/01d.svg
<img alt="" src={getImg(imgName)} />
function getImg(imgName) {
var fullPath = "icons/" + imgName + ".svg";
return require(fullPath);
}
If it still doesn't work, I suggest you to try with a static img and see if it loads. and try to figure out the path issue <img alt="" src={require('icons/01d.svg')} />
Upvotes: 0
Reputation: 1835
when you looping over an array you have a single object in each loop cycle, so you can do this
data = [{
img: '01d'
}, {
img: '02d'
}]
data && data.map((item) => (
<img src={`./icons/${item.img}.svg`} />
))
Upvotes: 0