Reputation: 1362
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.
Upvotes: 4
Views: 4294
Reputation: 15705
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>
)
}
Upvotes: 0
Reputation: 1559
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>
)
Upvotes: 7