9

This works no problem:

<Image source={require('./images/ace.png')} />

But this:

var name = 'ace';

<Image source={require('./images/' + name + '.png')} />

I've tried all kinds of variations but it always returns the error:

Requiring unknown module "./images/ace.png". If you are sure the module is there, try restarting the packager.

Hasen
  • 11,710
  • 23
  • 77
  • 135
  • I found this way works var name = require('./images/ace.png'); But it still doesn't solve the problem because you just can't concatenate anything or it throws that same error. Seems like a bug to me. – Hasen Nov 27 '15 at 10:55

3 Answers3

5

As per react native docs,

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

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

How about pre-declaring what is required and use it conditionally?

everlasto
  • 4,890
  • 4
  • 24
  • 31
1

Try using url

<Image
    style={styles.img}
    resizeMode={'contain'}
    source={{uri: imageURL}}>

and in imageURL which might be an URL

for example

var imageURL = 'http://assets22.pokemon.com/assets/cms2/img/pokedex/full/702.png'
Pramod Mg
  • 2,316
  • 1
  • 11
  • 14
  • 2
    What about for local images though since this is an app. If I just have an image at './images/ace.png/ the uri command doesn't seem to work. It doesn't throw any error but it just doesn't display the image. – Hasen Nov 28 '15 at 02:16
  • If you develop for iOS you can use the assets name from xcassets as uri (e.g.: source={{ uri: 'cuteCat' + counter }} ) – d-vine Nov 28 '15 at 03:08
  • 1
    That way doesn't work anymore. Check here https://facebook.github.io/react-native/docs/images.html#content – Hasen Nov 29 '15 at 00:53
-1

Nowadays solution, component named Row:

const Row = (props) => {
  let employmentType;

  // Set my own image component dynamically
  if(props.SOME_CONDITION){
     employmentType = <Image source={require('image!Driver')} style={styles.employeeLogo} />
  }
  else{
     employmentType = <Image source={require('image!ANOTHERIMAGE')} style={styles.employeeLogo} />
  }

  return(
    <View style={styles.row_container} elevation={2}>

      {employmentType}
      <Text style={styles.row_text}>{'../Assets/Images/' + props.PictureUrl + '.png'}</Text>
      <Text style={styles.row_text}>{props.Fullname}</Text>
      <Text style={styles.row_text}>{props.EmploymentType}</Text>
    </View>
  );
};
Cami Rodriguez
  • 1,057
  • 4
  • 14
  • 30