Reputation: 5346
The Flatlist lets you define an ItemSeparatorComponent that receive as default props highlighted
and leadingItem
. The leading Item represents the item displayed before the Separator.
The problem is that I am using inverted
on my Flatlist and my Seperators now need to adapt to the next item instead of the previous one.
Is there any way to access the item displayed after the Separator? Something like a trailingItem?
Upvotes: 6
Views: 16227
Reputation: 10719
If you want to have the trailing item, you can use separators.updateProps
to add a custom property. Below I have used the example from the FlatList docs and modified it slightly. In this example we are highlighting the trailing separator of the clicked item and we are adding the trailingItem
to the props of ItemSeparatorComponent
.
#Output:
#Code:
JSX:
<View style={styles.container}>
<FlatList
ItemSeparatorComponent={(props) => {
console.log('props', props); // here you can access the trailingItem with props.trailingItem
return (<View style={{height: 5, backgroundColor: props.highlighted ? 'green' : 'gray'}} />);
}}
data={data}
inverted
renderItem={({item, index, separators}) => renderItem(item,index,separators)}
/>
</View>
renderItem:
const renderItem = (item, index, separators) => {
return (
<TouchableHighlight
key={item.key}
onPress={() => console.log('onPress')}
onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
onHideUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: false})}>
<View style={{backgroundColor: 'white', height: 50, justifyContent: 'center', alignItems: 'center'}}>
<Text>{item.id}</Text>
</View>
</TouchableHighlight>
);
}
#Explanation:
The whole magic happens here:
onShowUnderlay={() => separators.updateProps('trailing', {trailingItem: data[index+1], highlighted: true})}
From the docs we can see, that updateProps expects the following two parameters:
select (enum('leading', 'trailing'))
newProps (Object)
First we select trailing
, afterwards we can add our custom prop. We are adding the trailingItem
prop and we are overriding the highlighted
prop. Now we can access our props in the ItemSeparatorComponent with props.trailingItem (see above, i leaved a comment on the specific line).
#Working Example:
https://snack.expo.io/@tim1717/flatlist-separators
Upvotes: 12