Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we set speed to scrollTo() in React Native?

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?

like image 304
user3911840 Avatar asked Jun 29 '17 08:06

user3911840


People also ask

How do you auto scroll in React Native?

Auto scroll is provided out of the box by react native. The ScrollView component by react native has props to scroll to the desired co-ordinates on the screen. There are two such props in ScrollView: ScrollTo(): takes the x and y offset coordinates and scrolls to that position.

How do I style the scrollbar in React Native?

Create the custom scroll bar Next, to the content displayed, let's add a scroll bar. Add a View component whose height is set to 100% . This will display the scroll bar with as much height as the height of its parent container. The width in the above code snippet can be customized with the value you can provide.

How do I make a horizontal scroll view in React Native?

In the ScrollView, we can scroll the components in both direction vertically and horizontally. By default, the ScrollView container scrolls its components and views in vertical. To scroll its components in horizontal, it uses the props horizontal: true (default, horizontal: false).


1 Answers

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>
  )
}

like image 140
ejanson Avatar answered Dec 30 '22 14:12

ejanson