Is there a way to scroll to the top of a ScrollView
in response to a button press?
I can force a re-render
of the whole page but that seems very inefficient.
current. scrollTo with 0 to scroll the ScrollView to the top when it's pressed.
Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) .
If your list items are of equal height, you can use them to implement scrolling to a specific item by calling scrollTo({y:itemIndex * ROW_HEIGHT}) . Show activity on this post. I have published react-native-scroll-into-view, a library which enable "scrollIntoView" feature for React Native ScrollView.
ref
attribute to your ScrollView
component. Example: <ScrollView ref='_scrollView'>
onPress={() => { this.refs._scrollView.scrollTo(0); }}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With