react native use variable for image file

For anyone getting to know the react-native beast, this should help 🙂

I visited a couple of sites in the past too, but found it increasingly frustrating. Until I read this site here.

It’s a different approach but it eventually does pay off in the end.
Basically, the best approach would be to load all your resources in one place.
Consider the following structure

app  
   |--img
      |--image1.jpg
      |--image2.jpg
      |--profile
          |--profile.png
          |--comments.png
      |--index.js

In index.js, you can do this:

const images = {
    profile: {
        profile: require('./profile/profile.png'),
        comments: require('./profile/comments.png'),
    },
    image1: require('./image1.jpg'),
    image2: require('./image2.jpg'),
};

export default images;

In your views, you have to import the images component like this:

import Images from './img/index';

render() {
    <Image source={Images.profile.comments} />
}

Everybody has different means to an end, just pick the one that suits you best.

Da Man – Q: How is this answer using a variable?

Well, since require only accepts a literal string, you can’t use variables, concatenated strings, etc. This is the next best thing. Yes, it still is a lot of work, but now you can do something resembling the OP’s question:

render() {
  var images = { test100: "image100" };
  return (
    <View>
      <Text>
       test {images["test" + "100"]}
      </Text>
    </View>
  );
}

Leave a Comment