React Native - Image Require Module using Dynamic Names

This is covered in the documentation under the section "Static Resources":

The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

// GOOD
<Image source={require('image!my-icon')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />

// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />

However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.

http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets


RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):

The way I hacked my way through this problem:

I created a file with an object that stored the image and the name of the image:

export const ANIMAL_IMAGES = {
  dog: {
    imgName: 'Dog', 
    uri: require('path/to/local/image')
  },
  cat: {
    imgName: 'Cat on a Boat', 
    uri: require('path/to/local/image')
  }
}

Then I imported the object into the component where I want to use it and just do my conditional rendering like so:

import { ANIMAL_IMAGES } from 'path/to/images/object';

let imgSource = null;

if (condition === 'cat') {
  imgSource = ANIMAL_IMAGES.cat.uri;
}

<Image source={imgSource} />

I know it is not the most efficient way but it is definitely a workaround.

Hope it helps!


This worked for me :

I made a custom image component which takes in a boolean to check if the image is from web or is being passed from a local folder.

// In index.ios.js after importing the component
<CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>

// In CustomImage.js which is my image component
<Image style={styles.image} source={this.props.imageName} />

If you see the code, instead of using one of these:

// NOTE: Neither of these will work
source={require('../images/'+imageName)} 
var imageName = require('../images/'+imageName)

I'm just sending the entire require('./images/logo.png') as a prop. It works!