I have a horizontal flat list where each item is width:300
All I am trying to do is to get index of currently visible item.
<FlatList
onScroll={(e) => this.handleScroll(e)}
horizontal={true}
data={this.state.data}
renderItem...
Tried this:
handleScroll(event) {
let index = Math.ceil(
event.nativeEvent.contentOffset.x / 300
);
And something like this:
handleScroll(event) {
let contentOffset = event.nativeEvent.contentOffset;
let index = Math.floor(contentOffset.x / 300);
but nothing is accurate I always get one index up or one index down.
What am I doing wrong and how to get correct current index in flat list?
For example I get to list item that is 8th in a list but I get index 9 or 10.
UPD. thanks to @ch271828n for pointing that onViewableItemsChanged shouldn`t be updated
You can use FlatList onViewableItemsChanged
prop to get what you want.
class Test extends React.Component {
onViewableItemsChanged = ({ viewableItems, changed }) => {
console.log("Visible items are", viewableItems);
console.log("Changed in this iteration", changed);
}
render () => {
return (
<FlatList
onViewableItemsChanged={this.onViewableItemsChanged }
viewabilityConfig={{
itemVisiblePercentThreshold: 50
}}
/>
)
}
}
viewabilityConfig
can help you to make whatever you want with viewability settings. In code example 50
means that item is considered visible if it is visible for more than 50 percents.
Config stucture can be found here