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?
<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}
/>
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 prop to render some JSX or a component at the end of the list.
If you need to know that you are at the end of the list within 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>
);
}
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}
/>