I'm having issues writing an If statement in React Native. I'm building the mobile version of my React Js project where I already have the "if" statement but I'm not being able to write it in Native.
Here is what I got so far:
{renderItems && (
<FlatList
data={data}
keyExtractor={(item)=>{return item.date}}
numColumns={numberOfCols}
renderItem={({item})=>(
#######################################
if (item.copyright "exists" return (
<Image source(require(a specific local image)/>
else( return the code below
#######################################
<View style={styles.viewpic}>
<TouchableOpacity onPress={() => navigation.navigate('ImageDetails',
item)}>
<Image
style={{
height: 104,
width: square - 20,
margin: 10,
borderWidth: 1,
borderColor:'white',
borderRadius:2,
}}
source={{uri:item.url}}/>
</TouchableOpacity>
</View>
)}
/>)
}
the code works fine without the if part. I tried a few combos with "{" ,"(" ,"({" but nothing worked.
Thanks everyone for your help! Cheers,
CodePudding user response:
here
{renderItems &&
<FlatList
data={data}
keyExtractor={(item)=>{return item.date}}
numColumns={numberOfCols}
renderItem={({item})=>(
item.copyright== "exists" ?
<Image source(require(a specific local image)/>
:<View style={styles.viewpic}>
<TouchableOpacity onPress={() => navigation.navigate('ImageDetails', item)}>
<Image style={{
height: 104,
width: square - 20,
margin: 10,
borderWidth: 1,
borderColor:'white',
borderRadius:2,
}}
source={{uri:item.url}}/>
</TouchableOpacity>
</View>)}
/>
}
CodePudding user response:
Yes, there seem to be some missing brackets. I would create a separate function like check()
for the if
statements and let it return the JSX elements instead:
const check = (item) => {
if (item.copyright === "exists") {
return (
<Image source={require('a specific local image')}/>
)
}
else {
return (
<View style={styles.viewpic}>
<TouchableOpacity onPress={() => navigation.navigate('ImageDetails', item)}>
<Image style={{
height: 104,
width: square - 20,
margin: 10,
borderWidth: 1,
borderColor:'white',
borderRadius:2,
}}
source={{uri:item.url}}
/>
</TouchableOpacity>
</View>
)
}
}
{renderItems && (
<FlatList
data={data}
keyExtractor={(item)=>{return item.date}}
numColumns={numberOfCols}
renderItem={({item})=>(
check(item)
)}
/>
)}
If you do not want a separate function you have to write the function in the Flatlist's renderItem
a little bit different:
<FlatList
data={data}
keyExtractor={(item)=>{return item.date}}
numColumns={numberOfCols}
renderItem={({item})=> {
if (item.copyright === "exists") {
return (
<Component1/>
)
}
else {
return (
<Component2/>
)
}
}
}
/>
But still check for the brackets. They should all be correct in the first code snippet though.