Reputation: 476
I'm building a custom bottomnavbar for my app, and I'm running into a problem with linking the svg icons. Here is my code:
// Imports
class MainTabNavigation extends React.Component {
render() {
const navigationOptions = ['Dashboard','Status','Referrals','More'];
return(
<View style={styles.navBar}>
{
navigationOptions.map(nav => {
const lowerCaseString = nav.toLowerCase();
const svgPath = `../../assets/icons/${lowerCaseString}.svg`;
if (this.props.navigation.isFocused(nav)) {
return(
<TouchableOpacity style={[styles.tab,styles.focused]} onPress={() => {this.props.navigation.navigate(nav)}}>
<SvgUri source={require(svgPath)} />
<Text style={styles.captionStyle}>nav</Text>
</TouchableOpacity>
);
} else {
return(
<TouchableOpacity style={styles.tab} onPress={() => {this.props.navigation.navigate({nav})}}>
<SvgUri source={require(svgPath)} />
<Text style={styles.captionStyle}>{nav}</Text>
</TouchableOpacity>
);
}
})
}
</View>
);
}
}
// Styles
const NavigationConnected = withNavigation( MainTabNavigation );
export { NavigationConnected as MainTabNavigation };
And the error message is very strange. The error message says:
calls to `require` expect exactly 1 string literal argument, but this was found: `require(svgPath)`.
What I can't understand is that svgPath
is literally (excuse the pun) one string literal. I understand that I'm concatenating the string, but it is still just one string literal. So my question is two fold:
1. Why is the variable svgPath
not one string literal?
2. How can I dynamically build my svg paths through my map() call?
Upvotes: 0
Views: 454
Reputation: 152
In order for this to work, the image name in require has to be known statically.
// 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} />;
ref: https://facebook.github.io/react-native/docs/images.html
Upvotes: 1