I have component in application with SectionList which parses its content from local json file. List item has image and text and when require image using varibale it causes error: calls to require expect exactly 1 string literal argument, but this was found: item.logo
.
My json file
{
"algorithms":[
{"title":"Sorting algorithms","logo":"../logos/sorting.png"},
{"title":"Graph theory","logo":"../logos/graph.png"},
{"title":"Strings","logo":"../logos/strings.png"},
{"title":"Greedy technique","logo":"../logos/greedy.png"},
{"title":"Dynamic programming","logo":"../logos/dp.png"}
],
"datastructures":[
{"title":"Trees","logo":"../logos/tree.png"},
{"title":"Lists","logo":"../logos/list.png"},
{"title":"Tries","logo":"../logos/trie.png"},
{"title":"Stack and Queue","logo":"../logos/stack.png"},
{"title":"Hash Tables","logo":"../logos/hashtable.png"}
]
}
And renderItem
function
renderItem = ({item}) => {
return(
<TouchableWithoutFeedback onPress={()=>this.props.navigation.navigate('List')}>
<View style={styles.itemHolder}>
<Image resizeMode="center" style={styles.itemLogo} source={require(item.logo)}/>
<View style = {styles.itemNameHolder}>
<Text style = {styles.itemName}>{item.title}</Text>
</View>
<View style={styles.itemPointer}>
<Image style={{width:50,height:50,}} source={require('../icons/right-arrow.png')}/>
</View>
<Divider/>
</View>
</TouchableWithoutFeedback>
);
}
Edited
Function require
in js does not work dynamically. It's argument must be string.
Edit: I think you need to use a workaround of map
first, you need to find a way to make the logo format to be like this
const data = [
{"title":"Sorting algorithms","logo": require('../logos/sorting.png')},
{"title":"Graph theory","logo": require('../logos/graph.png')},
]
Then when you want to use it just do like this
render() {
return (
<View>
{data.map((item) => {
<View>
<Image
style={styles.image}
source={item.logo}
/>
</View>
})}
</View>
);
}
let me know if it is work or not