Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep scroll position using flatlist when navigating back in react native ?

Tags:

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.

like image 413
Pulkit Aggarwal Avatar asked Jan 02 '18 12:01

Pulkit Aggarwal


People also ask

How do you keep the scroll position with FlatList?

In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen. I am using Expo version 25.

How do you handle scroll position in react?

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.

Is FlatList scrollable React Native?

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.

How get position of ScrollView in React Native?

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.


1 Answers

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)   }) }  
like image 77
Marcos Demétrio Avatar answered Sep 17 '22 18:09

Marcos Demétrio