0

I'm making a country picker with flags. The country names and flag image name is coming from database, like this (sample):

dataSource: [
{
  id: 1,
  name: "Afghanistan",
  image: '../assets/flags/af.png'
},
{
  id: 2,
  name: "Bahrain",
  image: '../assets/flags/ba.png'
},
{
  id: 3,
  name: "Canada",
  image: '../assets/flags/ca.png'
}]

Then I send that dataSource to my component

                        <CountryPickerFlags
                          dataSource={this.state.dataSource}
                        />

Then in the component FlatList (renderItem) I do:

  _renderItemListValues(item, index) {
      var image_uri = {uri: item.image} ;   
      
      console.log(JSON.stringify(image_uri));
        
    return (
    
      <TouchableOpacity
        activeOpacity={1}
        style={styles.listRowClickTouchStyle}
        onPress={() => this._setSelectedIndex(item.id, item.name)}
      >
        <View style={[styles.listRowContainerStyle,{ flexDirection:'row', justifyContent: 'center', alignItems: 'center'}]} >
          <Image source={image_uri} />
          <Text style={styles.listTextViewStyle}>{item.name}</Text>
        </View>
      </TouchableOpacity>
    );
  }

But the flag is not rendered.... If I hardcode the image (with require) it's working...

  <Image source={require("../assets/flags/af.png")} />

How can I do it?

Marco Martin
  • 185
  • 1
  • 4
  • 18

2 Answers2

1

Go to assets folder and create a file prepareImages.js and paste inside the following:

const fs = require("fs");
const files = fs.readdirSync("./assets/flags").filter(x => x.includes("png"));
const ex = "{\n" +
files.map(x => `"../assets/flags/${x}": require("./${x}"),`).join("\n") + "}";
const res = "export default " + ex;
fs.writeFileSync("./assets/flags/index.js", res);

This will create an index.js file where will be an object like that:

"../assets/flags/af.png": require("./af.png"),

Import images from this file where you render Image component.

import images from "../assets/flags/images";

Render image source like that:

<Image source={images[image_uri]} />
Leri Gogsadze
  • 2,958
  • 2
  • 15
  • 24
0

Add require to your data set like

dataSource: [ { ..., image: require('../assets/flags/af.png')}]
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39