react-nativereact-native-iosreact-componentreact-image

React Native 'require' statement resolves to a number when used in mapping


I understand that require('') needs a static string, but when I try to map values in packaging to be used later in code

const BOXES2 = {
  silver: require('../../assets/imgs/status/silveroutline.png'),
  gold: require('../../assets/imgs/status/goldoutline.png'),
  platinum: require('../../assets/imgs/status/platinumoutline.png')
}

they resolve to integers , the following logs the number 6

constructor(props) {
    super(props);
    var data = BOXES2[this.props.userData.memberStatus];
    console.log(data);
  }

so then I cannot load images like this

<Image
        source={BOXES2[this.props.userData.memberStatus]}
        style={img}
        resizeMode="contain"
      />

memberStatus is a string value and the data and image paths are correct, as I can get it to work by creating a separate Image using each source path directly in render(), and then placing one of them in return() conditionally by the userData.

I would like to figure the other way out though, as it requires many many less lines and much easier to maintain.


Solution

  • keep all require statements in seperate file like

    image.js

    export default {                                                                
      silver: require('../../assets/imgs/status/silveroutline.png'),
      gold: require('../../assets/imgs/status/goldoutline.png'),
      platinum: require('../../assets/imgs/status/platinumoutline.png')
    };
    

    and import this file in your screen like this:

    import BOXES2 from 'src/config/Images';
    

    after importing use image component like this:

     eg: <Image
             source={BOXES2[this.props.userData.memberStatus]}
             style={img}
             resizeMode="contain"
         />