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

kalyani_jamunkar picture kalyani_jamunkar · Feb 6, 2018 · Viewed 13.9k times · Source

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.

Answer

Aaditya Thakkar picture Aaditya Thakkar · Feb 6, 2018

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().