MrV
MrV

Reputation: 203

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

Upvotes: 4

Views: 2408

Answers (2)

Emad Baqeri
Emad Baqeri

Reputation: 2702

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.

Upvotes: 2

brentvatne
brentvatne

Reputation: 8038

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.

Upvotes: 2

Related Questions