Reputation: 1635
Was trying to conditionally return items in a flatlist but it is not returning anything in react native. Thanks in advance
<FlatList
data={posts}
ref={(c) => {this.flatList = c;}}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => {
item.categories_name.map(category=>{
let cat = category.toLowerCase();
if(cat=='movie'){
<Text style={{fontSize:20,color:'white'}}>This is movie</Text>
}
else(
<Text style={{fontSize:20,color:'white'}}>This is normal post</Text>
)
}
})
//<PostItem onImagePress={()=>this.toggleModal(item.id)} route={this.state.route_name} post={item}/>
}
}
/>
Upvotes: 1
Views: 334
Reputation: 755
You need to return the JSX elements when using renderItem.
when you see renderItem={({item}) => <Text>{item.key}</Text>}
. It is the shorthand of:
renderItem={({item}) => {
return <Text>{item.key}</Text>
}}
So something like below should work:
<FlatList
data={posts}
ref={(c) => {this.flatList = c;}}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => {
return item.categories_name.map(category=>{
let cat = category.toLowerCase();
if(cat=='movie'){
return <Text style={{fontSize:20,color:'white'}}>This is movie</Text>
} else {
return <Text style={{fontSize:20,color:'white'}}>This is normal post</Text>
}
})
...
You should notice above that renderItem returns
whatever .map
returns (which should be an array of JSX elements. This return
inside .map fn is also necessary: return <Text style...
because that's how you want to use .map
, *you want to return array of elements* If that is not so clear please check .map
and figure that out on your own. That should help you better
I hope this helps
Upvotes: 1
Reputation: 951
Can you re-arrange your code to the following?
<FlatList
data={posts}
ref={c => {
this.flatList = c;
}}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => {
let views = [];
item.categories_name.map(category => {
let cat = category.toLowerCase();
if (cat == "movie") {
views.push(
<Text style={{ fontSize: 20, color: "white" }}>
This is movie
</Text>
);
} else {
views.push(
<Text style={{ fontSize: 20, color: "white" }}>
This is normal post
</Text>
);
}
});
return views;
//<PostItem onImagePress={()=>this.toggleModal(item.id)} route={this.state.route_name} post={item}/>
}}
/>
Upvotes: 2