How can I add a separator for every 3 items in flatlist? I can just add a separator after every 1 item. I did not find a prop for that. Here are my codes:
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text} from 'react-native';
const DATA = [
{
id: 1,
title: 'Item 1',
},
{
id: 2,
title: 'Item 2',
},
{
id: 3,
title: 'Item 3',
},
{
id: 4,
title: ' Item 4',
},
{
id: 5,
title: 'Item 5',
},
{
id: 6,
title: 'Item 6',
},
{
id: 7,
title: 'Item 7',
},
];
const App = () => {
const renderItem = ({ item }) => (
<View style={styles.item}>
<Text style={styles.title}>{item.title}</Text>
</View>
);
const seperator = () => {
return (
<View style={styles.seperator} />
)
}
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(items) => items.id}
ItemSeparatorComponent={seperator}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
backgroundColor: '#f9c2ff',
padding: 10,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
seperator: {
width: 300,
height: 10,
backgroundColor: 'red'
}
});
export default App;
My app looks likes:
But I want to make that:
How can I add a separator for every 3 items in flatlist? I can just add a separator after every 1 item. I did not find a prop for that.
In case your data items do not have an id or a property that can easily distinguish two items, consider using a counter to keep track of how many times your separator function was called.
However, it is important to work with some key in keyExtractor, because it is used for caching and as the react key to track item re-ordering.
For this case, anyways, useRef hook can be used, since:
useRef returns a mutable ref object whose .current property is initialized to the passed argument
Note that it would still be doable if you've chosen useState hook instead, but probably more verbose.
import { useRef } from 'react'
let count = useRef(0)
const seperator = (e) => {
count.current += 1
return (
(count.current % 3 == 0) ? <View style={styles.seperator}/>
: null
)
}
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
ItemSeparatorComponent={(e) => seperator(e)}
/>
</SafeAreaView>
)
Since it's mutable, add one unit each time the function is called
First, pass an arrow function receiving an argument. In this case, it's e, which holds the object (for instance the first):
{"highlighted":false,"leadingItem":{"id":1,"title":"Item 1"}}
So it's an easy approach, get the id and check if its %3 === 0. Take a look:
const seperator = (e) => {
return (
(e.leadingItem.id % 3 == 0) ? <View style={styles.seperator}/>
: null
)
}
And then
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(items) => items.id}
ItemSeparatorComponent={(e) => seperator(e)}
/>
</SafeAreaView>
);
As you can see in this working example