Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Flatlist from scrolling when new items are added

Tags:

react-native

When adding data to the Flatlist (e.g. subscriptions) it scrolls down leading to a very bad UX. Any idea on how this could be solved?

like image 933
Ragnor Avatar asked Apr 25 '17 13:04

Ragnor


People also ask

How do I stop my FlatList from scrolling?

To enable or disable scrolling on FlatList with React Native, we can set the scrollEnabled prop. to set the scrollEnabled prop to false to disable scrolling on the FlatList.

What is offset in FlatList?

'offset' (number) - The offset to scroll to. In case of horizontal being true, the offset is the x-value, in any other case the offset is the y-value.

Why FlatList React Native to keyExtractor?

Conclusion. When using a FlatList component, if the data array has a unique id or a key property, you do not need to use the keyExtractor prop explicitly. But for custom id names, use the keyExtractor prop to explicitly tell the component which unique key to extract.

What does the key extractor prop of the FlatList do?

The keyExtractor prop In our code sample above, notice that we used a FlatList property called keyExtractor . This prop is useful for extracting an identifier for a given item at the specified index. By default, keyExtractor uses the item. key or the item.id key as an identifier from the array.


1 Answers

Actually, I think this must be handled in native level, but not handled yet, I solve my problem by saving scroll offset and set it again after reloading data like this:

reloadData(flatListData){

   this.setState({
       flatListData: flatListData
   });

   requestAnimationFrame(() => {
         this.flatList.scrollToOffset({
                       animated: false,
                       offset: this.flatListLastOffset
             });
   });
}

...

<FlatList
     data={this.state.flatListData}
     ref={ref => this.flatList = ref}
     onScroll={(event: Object) => {
           this.flatListLastOffset = event.nativeEvent.contentOffset.y;
           }}
     horizontal={false}
     scrollEventThrottle={16}
 />

this is not the best solution, but can fix my problem for now

like image 63
Amir Khorsandi Avatar answered Sep 30 '22 00:09

Amir Khorsandi