Search code examples
react-nativescrollview

React-Native automatically scroll down


I have an app with one ScrollView and a button and a long text inside inside:

return (
    <ScrollView>
        <Button onPress={slowlyScrollDown} title="Slowly scroll a bit down..." />
        <Text>
              [ Very long text here where user has to scroll ]
        </Text>
    </ScrollView>
)

When the user presses the button, I want to slowly scroll down a bit, like that he can see like the first 5-10 lines of the Text.

I would accept any answer that provides a piece of code how I can implement that.


Solution

  • I am not sure it will work but that is the direction:

    const [offset,setOffset] = useState(0);
    const scrollViewRef = useRef();
    
    const slowlyScrollDown = () => {
        const y = offset + 80;
        scrollViewRef.current.scrollTo({x: 0, y, animated: true});
        setOffset(y);
    }
    
    return (
        <ScrollView ref={scrollViewRef} >
            <Button onPress={slowlyScrollDown} title="Slowly scroll a bit down..." />
            <Text>
                  [ Very long text here where user has to scroll ]
            </Text>
        </ScrollView>
    )