13

I'm scroll the page on click of a button using:

this.scrollTo({y: height, x: 0, animated: true})

The scroll works fine, however I'd like to slow down the scroll animation. How do we do that?

user3911840
  • 151
  • 2
  • 6

2 Answers2

2

This is a pretty neat solution that uses the scrollview's content height to scroll an entire view (on mount). However, the same trick can be used (add a listener to an animated value) to create a scroll function that can be triggered by some event at any given moment (to any given value).


import { useEffect, useRef, useState } from 'react'
import { Animated, Easing, ScrollView } from 'react-native'

const SlowAutoScroller = ({ children }) => {
  const scrollRef = useRef()
  const scrollAnimation = useRef(new Animated.Value(0))
  const [contentHeight, setContentHeight] = useState(0)

  useEffect(() => {
    scrollAnimation.current.addListener((animation) => {
      scrollRef.current &&
        scrollRef.current.scrollTo({
          y: animation.value,
          animated: false,
        })
    })

    if (contentHeight) {
      Animated.timing(scrollAnimation.current, {
        toValue: contentHeight,
        duration: contentHeight * 100,
        useNativeDriver: true,
        easing: Easing.linear,
      }).start()
    }
    return () => scrollAnimation.current.removeAllListeners()
  }, [contentHeight])

  return (
    <Animated.ScrollView
      ref={scrollRef}
      onContentSizeChange={(width, height) => {
        setContentHeight(height)
      }}
      onScrollBeginDrag={() => scrollAnimation.current.stopAnimation()}
    >
      {children}
    </Animated.ScrollView>
  )
}

ejanson
  • 469
  • 8
  • 16
0

On android you can use the smoothScrollTo option

Anis D
  • 761
  • 11
  • 25