Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation: Scroll to top if tab is the same as active tab

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?

like image 436
Fabrizio Giordano Avatar asked Feb 18 '18 07:02

Fabrizio Giordano


2 Answers

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

like image 151
Constantin Predescu Avatar answered Sep 22 '22 07:09

Constantin Predescu


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

like image 40
Siraj Alam Avatar answered Sep 22 '22 07:09

Siraj Alam