I am new to react native. I am facing problem in maintaining the position of flatlist when navigating forward and then come back to that screen.
Current behavior
When navigating forward and then back, the scroll position is lost.
Expected behavior
When navigating on an extensive list of items, the user scrolls down the list and click on some item. The app goes to the next page which shows the product details. If the user decides do navigate back, the page does not scroll to the previous point.
In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen. I am using Expo version 25.
To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.
Under the hood, FlatList uses the ScrollView component to render scrollable elements. However, unlike generic ScrollView, FlatList displays data lazily to save memory and processing time. Let's begin with the first method of rendering list data in a React Native app using the map function.
To get the current scroll position of ScrollView in React Native, we can set the onScroll prop of the ScrollView to a function that takes the scroll event object as an argument.
Try handling scroll position changing on a state:
<FlatList onScroll={this.handleScroll} />
handleScroll method:
handleScroll: function(event: Object) { this.setState({ scrollPosition: event.nativeEvent.contentOffset.y }); }
Then you can use scrollToOffset(this.state.scrollPosition) when you navigate back.
If you use react-navigation and want to keep the scroll position after navigation, try this hack:
componentDidMount() { this.props.navigation.addListener('willBlur', () => { const offset = this.state.scrollPosition // To prevent FlatList scrolls to top automatically, // we have to delay scroll to the original position setTimeout(() => { this.flatList.scrollToOffset({ offset, animated: false }) }, 500) }) }
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