Reputation: 636
I have a FlatList.
I want to add comma between items.
Currently working like this;
If there is only one item;
Mon,
If there are multiple items;
Mon, Tue, Wed,
My code;
<FlatList
data={job.schedule}
renderItem={({ item, index }) => (
<View style={[[Layout.center], {}]}>
<Text style={[[Fonts.textInterRegular12]]}>
{item.dayHuman.slice(0, 3)}{', '}
</Text>
</View>
)}
horizontal
keyExtractor={item => item.id}
extraData={this.state}
showsVerticalScrollIndicator={false}
/>
Above code has two issues.
If there is only one item, I don't want to add a comma.
E.g. Mon
If there are multiple items, I don't want to add a comma next to the last item.
E.g. Mon, Tue, Wed
How can I achieve this?
Upvotes: 6
Views: 9136
Reputation: 20821
When working with ReactNative FlatList, you can use FlatList's ItemSeparatorComponent
prop to render a component between each item, but not at the start or end of the list.
You can use FlatList's ListFooterComponent
& ListHeaderComponent
props to render some JSX or a component at the end or start of the list.
See diagram below.
If the above doesn't help and you just need to know that you are at the end of the list within a renderItem
, you can check the index
in the metadata provided to renderItem
against the length of data
.
const data = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
export default function App() {
return (
<SafeAreaView>
<FlatList
data={data}
renderItem={({ item, index }) => {
const isEnd = index === data.length - 1;
return (
<View>
<Text>
{item}{isEnd && <Text>. </Text>}
</Text>
</View>
);
}}
horizontal
keyExtractor={(item) => item.id}
extraData={this.state}
showsVerticalScrollIndicator={false}
ItemSeparatorComponent={() => <Text>, </Text>}
ListFooterComponent={() => <Text>The End!</Text>}
/>
</SafeAreaView>
);
}
Upvotes: 15
Reputation: 73
I think you are looking for this
<FlatList
data={job.schedule}
renderItem={({ item, index }) => (
<View style={[[Layout.center], {}]}>
<Text style={[[Fonts.textInterRegular12]]}>
{item.dayHuman.slice(0, 3)}{index < job.schedule.length -1 ?', ':""}
</Text>
</View>
)}
horizontal
keyExtractor={item => item.id}
extraData={this.state}
showsVerticalScrollIndicator={false}
/>
Upvotes: 0
Reputation: 6962
<FlatList
data={job.schedule}
renderItem={({ item, index }) => (
<View style={[[Layout.center], {}]}>
<Text style={[[Fonts.textInterRegular12]]}>
{item.dayHuman.slice(0, 3)}
{index !== job.schedule.length -1 && ', '}
</Text>
</View>
)}
horizontal
keyExtractor={item => item.id}
extraData={this.state}
showsVerticalScrollIndicator={false}
/>
Upvotes: 1