0

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:

Red Screen log

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.

Taylon Assis
  • 332
  • 1
  • 6
  • 16
  • Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – jmargolisvt Apr 12 '18 at 19:34
  • is the second parameter ok? the `_icon2.default` do you have a `_icon2.default.png` ? – oma Apr 13 '18 at 06:54
  • That's what I am not understanding, this `_icon2.default`not even exist in my code. The parameters are (item.icon,icon.direcao) – Taylon Assis Apr 13 '18 at 13:26

0 Answers0