I have a tab-based app. If I'm currently on the first tab, scrolled all the way down, and I click the tab again, I want it to scroll to the top. Is this possible?
I know I should have a scroll view with a reference and then use this._scrollView.scrollTo(0)
, but how can I detect when the user taps the tabbar and decide whether it is the same tab?
For who is looking for a solution for react native, if you are using react navigation, you need to import ScrollView, FlatList or SectionList from react-navigation instead of react-native.
eg.
import { FlatList } from 'react-navigation';
You can find the details on the docs: https://reactnavigation.org/docs/4.x/scrollables/
UPDATE
If you are using react navigation v5
import * as React from 'react';
import { FlatList } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';
function CustomComponent() {
const ref = React.useRef(null);
useScrollToTop(ref);
return <FlatList ref={ref} {/* settings */} />;
}
docs: https://reactnavigation.org/docs/use-scroll-to-top
React Navigation 5.x
The simplest solution they have provided is, just pass the ref of your scrollable component to their useScrollToTop
hook.
import * as React from 'react';
import { ScrollView } from 'react-native';
import { useScrollToTop } from '@react-navigation/native';
function Albums() {
const ref = React.useRef(null);
useScrollToTop(ref);
return <ScrollView ref={ref}>{/* content */}</ScrollView>;
}
Snack.expo.io Example
Documentation
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