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;

128 thoughts on “React Load Images and Dynamically Display in Component”

Leave a Comment