Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to top of ScrollView

Tags:

react-native

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.

like image 736
George B Avatar asked Aug 07 '15 17:08

George B


People also ask

How do I scrollTo the top of ScrollView?

current. scrollTo with 0 to scroll the ScrollView to the top when it's pressed.

How do I scrollTo the top of the page in React Native?

Use the window. scrollTo() method to scroll to the top of the page in React, e.g. window. scrollTo(0, 0) .

How do you scrollTo particular view in React Native?

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.


2 Answers

  1. First add a ref attribute to your ScrollView component. Example: <ScrollView ref='_scrollView'>
  2. Then wherever you want to scroll to top do this Example: onPress={() => { this.refs._scrollView.scrollTo(0); }}
like image 104
Sritam Avatar answered Sep 24 '22 14:09

Sritam


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> 
like image 36
iman roosta Avatar answered Sep 22 '22 14:09

iman roosta