ScrollToEnd after update data for Flatlist

My issue here was that scrollToEnd() worked fine on mobile but on web it always scrolled to the top. Probably because I have elements with different size in the FlatList and couldn't define getItemLayout. But thanks to the accepted answer here I solved it. Just with different approach.

const ref = React.useRef<FlatList>();

function handleScrollToEnd(width, height) {
  if (ref.current) {
    ref.current.scrollToOffset({offset: height});
  }
}

<FlatList
  ref={ref}
  onContentSizeChange={handleScrollToEnd} 
/> 

This works great on both the mobile and web. Hope it helps to somebody.


const flatList = React.useRef(null)
<FlatList
        ref={flatList}
        onContentSizeChange={() => {
            flatList.current.scrollToEnd();
        }}
        data={this.state.data}
        extraData = {this.state}
        renderItem={({item}) => <Text style={styles.chatFlatListItem}>{item.chat}</Text>}
/>

try this,it works.


I found a better solution,scrollToEnd() is not working because it is triggered before the change is made to the FlatList.
Since it inherits from ScrollView the best way here is to call scrollToEnd() in onContentSizeChange like so :

<FlatList
            ref = "flatList"
            onContentSizeChange={()=> this.refs.flatList.scrollToEnd()} /> 

Thanks @Kernael, just add a timeout like so:

setTimeout(() => this.refs.flatList.scrollToEnd(), 200)