Reputation: 687
I'm using Flatlist
in HomeScreen and it shows me multiple posts. So now what I want is whenever I Signout from the app or close the app and then open the app, I should be able to see the first item from Flatlist
.
I've tried using scrollToIndex
inside my render function but it gave me an error - undefined is not an object (evaluating '_this2.refs.flatListRef.scrollToIndex')
<FlatList
data={this.state.data}
ref={(ref) => { this.flatListRef = ref; }}
renderItem={ ({item,index}) => this._renderItem(item,index) }
extraData={[ this.state.data, this.state.checked ]}
/>
And this is what I tried using in componentDidMount
and inside render function this.refs.flatListRef.scrollToIndex({animated: true,index:0});
but didn't work.
Upvotes: 3
Views: 2800
Reputation: 21
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';
const ref = React.useRef(null);
useScrollToTop(ref);
const goToTopClickAction = () => {
ref.current?.scrollTo({
y: 0,
animated: true,
});
};
// add ref={ref} in ScrollView tag
<ScrollView ref={ref}>
{ ... rest of your code ...}
</ScrollView>
Upvotes: 0
Reputation: 580
ComponentDidMount callbacks won't run after the user leaves the app and resumes it later. You have to use AppState instead:
AppState can tell you if the app is in the foreground or background, and notify you when the state changes. [Source]
Adapt the given example to your needs and scroll with this.flatListRef.scrollToIndex({animated: true,index:0})}
Upvotes: 1