3

I'm working on including some flags to represent countries in my react native project. I discovered that you can't dynamically require images like the example below in react native.

require(`../assets/flags/32/${countryCode}.png`)

So given the SO response I found here I was thinking of creating a function with a switch statement that would return the required image back when passed the correct flag code. Something like the below.

export const Flags = (countryCode) => {
 switch (countryCode) {
   case 'US':
    return require('../assets/flags/32/US.png');
   ....
 }
};

I'll have well over 200 cases given this solution. Is there some better way to do this?

Community
  • 1
  • 1
Cameron Barker
  • 141
  • 1
  • 9

1 Answers1

5

Because of how cumbersome it would be to manually require all the images, can you add them to your App image assets and require them via uri?

<Image source={{uri: 'flags/32/'+countryCode}} style={{width: 32, height: 32}} />

Other than that I think your proposal is the only other solution.. you could clean it up slightly by making it a JS module.

Flags.js

exports.US = require('../assets/flags/32/US.png')
exports.UK = require('../assets/flags/32/UK.png')
exports.FR = require('../assets/flags/32/FR.png')
exports.JP = require('../assets/flags/32/JP.png')
...

Then just reference it like so.

Component.js

import Flags from './Flags'

<Image source={Flags[countryCode]} style={{width: 32, height: 32}} />
BradByte
  • 11,015
  • 2
  • 37
  • 41