Scroll to top of ScrollView
Solution 1:
- First add a
ref
attribute to yourScrollView
component. Example:<ScrollView ref='_scrollView'>
- Then wherever you want to scroll to top do this Example:
onPress={() => { this.refs._scrollView.scrollTo(0); }}
Solution 2:
in functional components
import { useRef } from 'react';
const scrollRef = useRef();
const onPressTouch = () => {
scrollRef.current?.scrollTo({
y: 0,
animated: true,
});
}
<ScrollView ref={scrollRef}>
...your elements
</ScrollView>
<TouchableOpacity onPress={onPressTouch}></TouchableOpacity>
Solution 3:
You can run the "scrollTo" method of the ScrollView. Check out the source.
You can get reference the ScrollView component by setting ref property and using this.refs as described here: https://facebook.github.io/react/docs/more-about-refs.html
Solution 4:
A simple example:
<ListView
ref={ref => this.listView = ref}
onContentSizeChange={() => {
this.listView.scrollTo({y: 0})
}}
/>
Solution 5:
scrollTo(x, y)
is now deprecated. It's now best to pass an object to scrollTo
like this:
this.refs.scrollView.scrollTo({x: 0, y: 0, animated: true})