Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i scroll top on onPress of button in react-native?

I have added the button in bottom of simple screen and I want to scroll top whenever I press the button. what code to add to button onPress?, Please suggest any solution, Thanks in advance.

like image 593
kalyani_jamunkar Avatar asked Feb 06 '18 13:02

kalyani_jamunkar


People also ask

How do you scroll on button click React?

To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.


2 Answers

I am assuming you are using a ScrollView on your page since you want to scroll to the top whenever a button is pressed at the bottom. In that case, you can use scrollTo({x: 0, y: 0, animated: true}) method of ScrollView. You can call a function before the render method like this:

goToTop = () => {
   this.scroll.scrollTo({x: 0, y: 0, animated: true});
}
render() {
 return (
  <ScrollView
    ref={(c) => {this.scroll = c}}
  >
    // [rest of your code here...]
    <Button title='Go To Top' onPress={this.goToTop} />
  </ScrollView>
 )
}

Basically, you have to create a reference(ref) to your scrollView and then you can call its method anywhere in your code.

In case you are not using ScrollView, but instead, you are using the Flatlist component, it also has a method exposed via its refs called scrollToOffset().

like image 144
Aaditya Thakkar Avatar answered Oct 24 '22 06:10

Aaditya Thakkar


In React Native for functional component, need to do following things to work scroll Top in ScrollView-

1.Define globally in functional component :- const scroll = React.createRef();

  1. then, do add :- ref={scroll} in ScrollView.

3.Finally, on click add :- scroll.current.scrollTo(0); // will scroll to the top at y-position 0

like image 2
Yogesh Shingare Avatar answered Oct 24 '22 07:10

Yogesh Shingare