Reputation: 1
I'm trying to create a card game, so I downloaded 52 jpegs of cards and have them in a folder called JPEG in my src folder. I made an array of cards that looks like this:
const cards = [{
name: 'aceHearts',
value: 1,
img: './JPEG/AH.jpg'
}, {
name: 'aceDiamonds',
value: 1,
img: './JPEG/AD.jpg'
}
etc.
I'm trying to make it so that when a button is clicked, an image will change to whatever card is on top of the shuffled array, so like
<img src={cards[0].img} />
I tried importing the images in and that works, but it seems silly to me to have 52 imports at the top of my code. So I tried writing:
<img src={require('./JPEG/AH.jpg') />
and that works, the card is shown. But when I write
<img src={require(cards[0].img)} />
it tells me "Error: Cannot find module './JPEG/AH.jpg'" Which I don't understand, because it found it fine when I typed it out manually, but it can't find it when it's pulling it from the array? Is there any way to make this work, or should I be using an entirely different approach?
If it's relevant, the cards array is in a file called Cards.js which is in the src folder, and the JSX is in a file called App.js which is also in the src folder. I've imported cards into App and it seems to be able to access it fine.
Upvotes: 0
Views: 503
Reputation: 11
You can just add "" empty string on top something like:
<img src={require(""+cards[0].img)} />
Upvotes: 1