'react native - requiring unknown module

I have been trying to load local image files in ListView.

It does work when I hard code:

return <Image source={require('./public/image1.png')} style={{width: 60, height: 60}}/>

However, it doesn't work when I read the path of the image like this:

var path = rowData.thumbnail;
console.log(path); // './public/image1.png'
return <Image source={require(path)} style={{width: 60, height: 60}}/>

or like this:

return <Image source={require(rowData.thumbnail)} style={{width: 60, height: 60}}/>

with this error message,

Requiring unknown module"'./public/image1.png'". If you are sure the module is there, try restarting the packager or running "npm install".

Could you please give me an advice to read the path from the object? I attached the full code below. Thank you in advance.

class MyClass extends Component {
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    let data = importedData.map(function(d) {
      return {
        thumbnail: "'./public" + d.thumbnail + "'"
      }
    });
    this.state = {
      dataSource: ds.cloneWithRows(data)
    };
  }
  renderRow(rowData) {
    var path = rowData.thumbnail;
    return <View style={{flex: 1, flexDirection: 'row'}}>
      <Image source={require(path)} style={{width: 60, height: 60}}/>
    </View>
  }
  render() {
    return (
      <View style={{paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderRow}
        />
      </View>
    );
  }
}


Solution 1:[1]

According to the React-Native Docs there are a couple of ways to specify where your images come from:

Local Storage:

<Image source={require('./img/favicon.png')}/>

Network:

<Image source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}/>

Dynamic strings e.g. rowData.thumbnail can only be used for packaged images. See this issue.

If your images are loaded into images.xcassets on iOS and res/drawable on Android you can reference them by the filename like so:

<Image source={{uri:'thumbnailFileName'}}/>

or..

<Image source={{uri:rowData.thumbnail}}/>

You can also specify placeholders in the same way..

<Image source={{uri:rowData.thumbnail}} defaultSource={{uri:'placeholder'}}/>

Working demo - https://rnplay.org/apps/tsiGfQ

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1