OptimusPrime
OptimusPrime

Reputation: 859

React Load Images and Dynamically Display in Component

I have been trying for a few hours to get a react component to load an image of a playing card depending on the prop passed in. I have been looking online and the answers I find to this issue are confusing me.

Basically I have an assets/cards directory with an image for each card in a deck of 52 playing cards. I want to map the code for the card (e.g sJ 'jack of spades') to the corresponding image. I thought this would be simple, but it doesn't seem so. I have the code below, but the require part is not working. Is there a preferred design patter for doing this sort of thing?

let images = {};

function getCard(val) {
  if(val + 2 < 11) {
    return (val + 2).toString();
  } else {
    switch(val + 2) {
      case 11:
        return 'J';
      case 12:
        return 'Q';
      case 13:
        return 'K';
      case 14:
        return 'A';
    }
  }
}


function getSuit(val) {
  switch (val) {
    case 0:
      return 's';
    case 1:
      return 'd';
    case 2:
      return 'c';
    case 3:
      return 'h';
  }
}

for(let i=0;i<4;i++) {
  for(let j=0;j<13;j++) {
    images[`${getSuit(i)}${getCard(j)}`] = `../assets/cards/${getSuit(i)}${getCard(j)}.png`;
  }
}


const CardImage = (props) => {
  return (
    <img src={require(images[`${props.card}`])} alt={props.card} />
  );
}

export default CardImage;

UPDATE

The component is available at https://codesandbox.io/s/distracted-dan-es7tb?file=/src/App.js

Upvotes: 1

Views: 309

Answers (2)

amirreza mojarad
amirreza mojarad

Reputation: 331

you cant add src attribute like that import all images like this

import blah from '../assets/images/blah.png'

then you must return blah in your code for value of src instead of your code

Upvotes: 1

Lygis
Lygis

Reputation: 100

Maybe have className={name that changes depending on number you get} like so and then in css you tell which className has what cardImg behind it. You should use state to change className.

Upvotes: 0

Related Questions