Prevent Flatlist to scroll to top on content size changes

Viewed 1901

Inside a FlatList I have accordions (by react-native-paper). When I scroll to any position and open/close an accordion, The FlatList scrolls to the top of the screen. How should I prevent it?

in another word when an accordion gets expanded, the content size is changed. How to stay where the user was on content size changes. The current snippet does not work and the stored y position resets.

  const flatListRef = React.useRef<FlatList<any>>(null);
  const yOffset = React.useRef<number>(0);

           <FlatList
             ref={flatListRef}
             data={properties}
             renderItem={renderItem}
             keyExtractor={(item) => `${item.id}`}
             onContentSizeChange={() =>{flatListRef.current!.scrollToOffset({offset: yOffset.current, animated: false});}}
             onEndReached={onEndReached}
             onEndReachedThreshold={0}
             scrollEventThrottle={15}
             onScroll={(e) => {yOffset.current = e.nativeEvent.contentOffset.y;}}
             ListFooterComponent={<ActivityIndicator animating={loading} size="small" />}
  />

for instance, (inside onContentSizeChange conosle.log(yOffset.current)) if I scroll to yOffset 850 and exapnd the accordion there, in console I see two logs, 850, then 126 (which 126 returns to the top) which indicates, onScroll was called and yOffset changed.

1 Answers

Not sure about your question here, but if you don't want to scroll to top on accordion expansion, just remove onContentSizeChange and onScroll prop.

Also, if you want that on accordion press that should come on top of the screen just wrap the Accordion in a View and get the expanded height/xy coordinates of the View using the onLayout prop and then you can use the Flatlist's scrollToOffset() to scroll to that particular Accordion

Related