Using react-native component. I got a lot of images with similar names that I have to retrieve right in distinct files and parts of my code. So I create that function to resolve all that:
export default getIcone = (icon, direction) => {
var img = '../www/images/' + icon.toString() + '_' + direction + '.png';
return img;
}
It returns a string containing the right path. Problem is when I try t call it in component.
render() {
return(
<List>
<FlatList
data={this.state.monitorados}
renderItem={({item}) => (
<TouchableHighlight
onPress={() => console.log("pressed")}
>
<View style={{backgroundColor: 'white', height: 60}}>
<Text>{item.identificador} {getIcone(item.icon, item.direcao)}</Text>
<Image source={require(getIcone(item.icon, item.direcao))}/>
</View>
</TouchableHighlight>
)} />
</List>
);
}
In I got the right string path displayed at screen. Although, Image crashes:
This says: calls to require expected exactly 1 string literal arguments, but this was found: 'require((0, _icon2.default)(item.icon,icon.direcao))'
Edit: This question is different from other traditionals source images at certain points. The property source of Image component is not that good to work with dynamic images paths. React Native official docs explains:
// GOOD
<Image source={require('./my-icon.png')} />;
// 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} />
This answer solves the problem, but its a hard workaround. I have over 1000 images and I wonder if there is a more ingenious solution.