How to make React Native tabview scroll back to the top of a tab when changing the active index

876 views Asked by At

I have a screen with the following structure:

<ScrollView>
  <View style={styles.container}>
    <View style={styles.topPanel} />
    <View style={styles.titleSection}>
      <View>
        <Image style={styles.profilePicture} source={logos} />
      </View>
      <View style={styles.textComponent}>
        <TextComponent
          boldness="extraBold"
          style={styles.titleSection__title}>
          ...
        </TextComponent>
        <TextComponent
          boldness="semiBold"
          style={styles.titleSection__text}>
          ...
        </TextComponent>
      </View>
      <View style={styles.verticalLine} />
      <RatingAndLocation location={6} medianRating={4.2} />
      <View>
        <TextComponent
          boldness="semiBold"
          style={styles.titleSection__desc}>
          ...
        </TextComponent>
      </View>
      <View style={styles.verticalLine} />
    </View>
  </View>
  <TabView images={images} setGalleryIndex={setGalleryIndex} />
</ScrollView>

Tabview component contains react-native-tabview tabs that are scrollViews with content in it. I'm trying to set scrollView's scroll position like that:

navigation.addListener('blur', () => {
  scrollViewRef.scrollTo({ y: 0, x: 0, animated: true });
});

But it doesn't work. Nested scrollViews are not working. They don't fire onScroll event. Only the parent scrollview does that. I want to know if there is a way around this issue.

As I understand, you can't nest vertical scrollViews, but how else can you make each tab an individual scrollView and scroll to the top of it when changing index?

Here is how it all should look like:

enter image description here

1

There are 1 answers

0
K. Efkas On

In order to trigger the scrollTo function you have to wrap it inside a setTimeout

setTimeout(() => {
   scrollViewRef.scrollTo({ y: 0, x: 0, animated: true });
}, 1)