I'm having a lot of trouble scrolling to the top of my Flatlist so any help would be greatly appreciated!
Essentially it fetches the first 5 items from firebase, then when onEndReached is called we append the next 5 items to the list:
data: [...this.state.data, ...results]
For now I have a refresh button at the top of my view that does the following:
this.flatListRef.scrollToOffset({ animated: true, y: 0 });
If i click this when the first 5 items are rendered it scrolls to the top of the list as expected. The issue only occurs after the list has been appended to (I guess the items are off view?).
I have also tried 'ScrollToItem' however I'm guessing this doesn't work due to the following from React Native docs:
Note: Cannot scroll to locations outside the render window without specifying the getItemLayout prop.
Can anyone explain what is happening or know what I am doing wrong?
Thank you in advance!
getItemLayout: (not entirely sure what this does or how to work out length & offset etc)
getItemLayout = (data, index) => ( { length: 50, offset: 50 * index, index } ) return ( <View> <FlatList ref={(ref) => { this.flatListRef = ref; }} onScroll={this.handleScroll} data={this.state.data} keyExtractor={item => item.key} ListFooterComponent={this.renderFooter()} onRefresh={this.handleRefresh} refreshing={this.state.newRefresh} onEndReached={this.handleEndRefresh} onEndReachedThreshold={0.05} getItemLayout={this.getItemLayout} renderItem={this.renderItem} /> {this.state.refreshAvailable ? this.renderRefreshButton() : null} </View> );
Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) .
We would use Ref. scrollToIndex() inbuilt function of FlatList here. To use this function first we have to make a reference of our FlatList component then we can call this function.
In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen.
The correct syntax is
this.flatListRef.scrollToOffset({ animated: true, offset: 0 });
and you can also use
scrollToIndex
Just in case someone is lost on how to do this with hooks, here is an example
function MyComponent() { const flatListRef = React.useRef() const toTop = () => { // use current flatListRef.current.scrollToOffset({ animated: true, offset: 0 }) } return ( <FlatList ref={flatListRef} data={...} ... /> ) }
The main difference is that you access it by .current
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With