is it normal that react native’s ScrollView scrollTo method can triggle the onScroll function?

const handleCurrent = (index: number) => {
    scrollRef.current.scrollTo({ x: 0, y: index * 202, animated: true });
};

const handleOnScroll = () => {
  console.log("scrolling");
}

<Pressable onPress={() => handleCurrent(2)}>a button</Pressable>
<ScrollView
 ref={scrollRef}
 onScroll={handleOnScroll} />
.......
</ScrollView>

is there any way I can know if the scrollView scrolling triggered by hands or by the code(like the scrollTo method)?

I have some extra works to do in handleOnScroll function, but I don’t want execute the handleOnScroll function when I use scrollTo method.

onScroll will always be called when the component is scrolled, whether manually or programmatically. If you want to fire a callback only when the component is scrolled manually, you can use onScrollBeginDrag or onScrollEndDrag (docs here).

It doesn’t look to me like there’s a built-in way to react only to a programmatic scroll, but since you’re doing the triggering, you can perform whatever action you like when you call scrollTo.

Leave a Comment