2

I am using React Native's ScrollView's scrollTo method to animate the scroll view. How can I make this animation spring loaded, as in Animated.spring (without the use of a 3rd party library)?

Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389

1 Answers1

2

Track the scroll position

<ScrollView
    ref={(ref) => { this.scrollView = ref; }}
    onScroll={(event) => {
        this.scrollY = event.nativeEvent.contentOffset.y;
    }}
    scrollEventThrottle={16}
>

And then

scrollTo(y) {
    if (!this.scrollY) this.scrollY = 0;
    const animatedValue = new Animated.Value(this.scrollY);
    const id = animatedValue.addListener(({ value }) => {
        this.scrollView.scrollTo({ x: 0, y: value, animated: false });
    });
   Animated.spring(animatedValue, { toValue: y }).start(() => { animatedValue.removeListener(id); /* finished callback */ });
}
lolelo
  • 698
  • 6
  • 18