Finnnn
Finnnn

Reputation: 3580

Adding dynamic local images in a react native listview

I'm trying to load some local images in a simple app that I'm making using react native.

I'm following the guide here - https://facebook.github.io/react-native/docs/images.html

Unfortunately, that guide says the following:

Note that in order for this to work, the image name in require has to be known statically.

Which is why my code isn't working when I try to render rows in a list view:

renderRow(chat){
  return (
      <View style={ styles.row }>
        <Image
          source={require(`../images/${chat.image}`)} //this is the part that's not working. It can't require a dynamic path
          style={ styles.cellImage }
          />
      </View>
);
}

How can I achieve this? Or can you suggest another way that will work?

Upvotes: 0

Views: 767

Answers (1)

jasonmerino
jasonmerino

Reputation: 3240

It's quirky and odd, but if you have a set number of options for the images (which makes sense if the images are living in the project) then you can return the statically required image based on a given condition.

getSource() {
    if (condition) {
        return require( '../images/option-one' );
    } else {
        return require( '../images/default-option' );
    }
}

renderRow(chat){
    return (
        <View style={ styles.row }>
            <Image
                source={ this.getSource() }
                style={ styles.cellImage }
            />
        </View>
    );
}

Upvotes: 1

Related Questions