2

In react native there is a scrollTo function which programatically scrolls to a given x and y coordinate, animated or not.

https://facebook.github.io/react-native/docs/scrollview.html#scrollto

scrollTo({x: 0; y: 0; animated: true})

In some cases this is useful, but there are some cases in which I only want to scroll down for 100 pixels or scroll up for 200 pixels regardless of the position x,y on the screen. Is there a way to programatically do this in react-native currently.

ralzaul
  • 4,280
  • 6
  • 32
  • 51

1 Answers1

3

You can keep track of your current X and Y scroll position in state by doing something like what is mentioned in this answer. So for example:

<ScrollView
  ref={(scrollView) => { this._scrollView = scrollView; }}
  onScroll={this.handleScroll}
/>

handleScroll = (event: Object) => {
    this.setState({scrollX: event.nativeEvent.contentOffset.x, scrollY: event.nativeEvent.contentOffset.y})
}

Then you can move your scroll using scrollTo and the current position +/- whatever you wish. Example:

moveScroll = () => {
    this._scrollView.scrollTo({y: this.state.scrollY + 100});
}

Do read through the linked StackOverflow answer though to understand the caveats of how onScroll works. I'm also not checking to see if you hit the end/beginning of the scroll window so check your bounds as well.

Community
  • 1
  • 1
Michael Cheng
  • 9,644
  • 6
  • 46
  • 48