4

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.

2 Answers 2

7

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>
)
Sign up to request clarification or add additional context in comments.

Comments

0

Use scrollTo() to scroll to a given x, y offset, either immediately, with a smooth animation.

For that take a reference of the scroll view using useRef. then follow the below autoScroll() method to implement the programmatic scroll in your application.

import React, {useRef} from 'react';
import {  ScrollView, Text, Button  } from 'react-native';

export default function App() {

    const scrollViewRef = useRef();

    const autoScroll = () => {
        let offset = 0;
        setInterval(()=> {
            offset += 20
            scrollViewRef.current?.scrollTo({x: 0, y: offset, animated: true})
        }, 1000)
    }

    return (
        <ScrollView ref={scrollViewRef} >
            <Button onPress={autoScroll} title="Start scrolling" />
            <Text>
                [ long text ]
            </Text>
        </ScrollView>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.