Reputation: 183
I have an array completedTests
in my app, with one example of its contents being this (when I use console.log()
):
Array [
Object {
"difference": 140,
"id": "Practice Test 3",
"targetReached": false,
"testScore": "1400",
}
]
To display its contents I would use:
<View>
<FlatList
data={completedTests}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />
</View>
If the array is empty, I would set my array to be ["none"]
, and trying to display this causes the following error:
undefined is not an object (evaluating 'item.targetReached.toString`)
How do I conditionally render my FlatList
in the way I want?
Upvotes: 0
Views: 193
Reputation: 95
I think this might work in what you are trying to do there ...
<View>
{
completedTests[0] !== "none" ? (<FlatList
data={completedTests}
keyExtractor={item => item.id}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />) : (
<Text>None</Text>
)
}
</View>
so you check the array content and if it's not the ["none"]
then you can render flatList else something else or nothing.
Upvotes: 0
Reputation: 16334
Instead of setting your array to "none" use this approach
<FlatList
data={completedTests}
keyExtractor={item => item.id}
ListEmptyComponent={<Text>None</Text>}
renderItem={({ item }) => (
<View style={[styles.scoreOverview, { backgroundColor: '#596b96' }]}>
<Text>{item.id}</Text>
<Text>{item.testScore}</Text>
<Text>{item.targetReached.toString()}</Text>
<Text>{item.difference}</Text>
</View>
)} />
The ListEmptyComponent would render when the array you supply is empty
Upvotes: 1