Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do dynamic image source in react native (expo)?

I have a simple function to display a playing card in my react native (expo) project. It works when testing locally but not when building for a device (APK, etc). From my understanding it is because the string in require can not be dynamic. If that is the case, what is the best way to handle this issue?
Do I have to do a require for all 52 cards and then pick the appropriate variable for the source of that card? or is there a better way?

  export default function Card( { cardID, index, onCardClick }) {

  const rankIndex = cardID % 13;
  const rank = RANKS[rankIndex];
  const suitIndex = cardID / 13 | 0;
  const suit = SUIT[suitIndex];

  let cardImage = require('../../assets/game/cards/'+rank+suit+'.png');

  return (
    <TouchableOpacity style={[index && index != 0 && styles.cardMargin]} onPress={() => onCardClick(cardID)}>
        <Image style={styles.card} source={cardImage} />
    </TouchableOpacity>
  );
}

Thank you

like image 805
MrV Avatar asked Sep 12 '25 16:09

MrV


2 Answers

do something like this:

const cardImages = {
  AceSpades: require('../../assets/game/cards/acespaces.png'),
  AceClubs: require('../../assets/game/cards/aceclubs.png'),
  // etc..
};

you can generate this array from your filesystem by writing a little node script or create it manually.

metro bundler requires that imports are static.

like image 192
brentvatne Avatar answered Sep 14 '25 07:09

brentvatne


You should make a function that return all the images as an array and then select the index that of specific image that you want.

like image 22
Emad Baqeri Avatar answered Sep 14 '25 07:09

Emad Baqeri