callback to scrollToLocation in react native

4.4k views Asked by At

i'm trying to run a function after the scroll momentum is completed in my sectionList of react native.

After referring the documentation i found out about onMomentumScrollEnd . But the issue is onMomentumScrollEnd works only when we manually scroll the section list. But i'm using scrollToLocation within a function to scroll to the specific section. When using that onMomentumScrollEnd does not seem to trigger. How can i trigger this function when the scrolling is complete when using scrollToLocation

<SectionList
          sections={groupActivities}
          keyExtractor={(item) => item?.id?.toString()}
          ref={sectionList}
          getItemLayout={getItemLayout}
          onMomentumScrollEnd={() => console.log('ends')}
          renderItem={({ section: { title }, item, index }) => {
            const sectionTitle = String(title);
            return (
              <View style={activityContainer}>
                <MCard
                  startTime={getFormattedStartTime(item.duration?.start)}
                />
              </View>
            );
          }}
          renderSectionHeader={({ section: { title } }) => (
            <MText>
              {setSectionTitle}
            </MText>
          )}
          refreshing={groupActivityLoading}
          onRefresh={handleRefresh}
        />
1

There are 1 answers

2
Tiago On

how are you triggering the scrollToLocation?

Please check my example using refs:

  const Example = () => {
  const sectionListRef = useRef(null);

  return (
    <SafeAreaView style={styles.container}>
      <Button
        title="Scroll"
        onPress={() => {
          sectionListRef.current.scrollToLocation({
            itemIndex: 6,
          });
        }}
      />
      <SectionList
        ref={sectionListRef}
        onMomentumScrollEnd={() => alert('ends')}
        sections={DATA}
        keyExtractor={(item, index) => item + index}
        renderItem={({item}) => <Item title={item} />}
        renderSectionHeader={({section: {title}}) => (
          <Text style={styles.header}>{title}</Text>
        )}
      />
    </SafeAreaView>
  );
};

Code running


Full code: If you want to test on your device here's the full code:

https://gist.github.com/tiagotedsky/076887546530a509ee602318f92ca7ac