iosreactjsreact-native

Get current scroll position of ScrollView in React Native


Is it possible to get the current scroll position, or the current page of a <ScrollView> component in React Native?

So something like:

<ScrollView
  horizontal={true}
  pagingEnabled={true}
  onScrollAnimationEnd={() => { 
      // get this scrollview's current page or x/y scroll position
  }}>
  this.state.data.map(function(e, i) { 
      <ImageCt key={i}></ImageCt> 
  })
</ScrollView>

Solution

  • Try.

    <ScrollView onScroll={this.handleScroll} />
    

    And then:

    handleScroll: function(event: Object) {
     console.log(event.nativeEvent.contentOffset.y);
    },
    

    In another context, let's say you also want to implement a pagination indicator, you'll want to go further by doing this:

    <ScrollView
         onScroll={Animated.event([{ nativeEvent: { contentOffset: { x: 
         scrollX } } }], {listener: (event) => handleScroll(event)})}
         scrollEventThrottle={16}
    >
       ...some content
    </ScrollView>
    

    where scrollX would be an animated value you can use for you pagination and your handleScroll function can take the form:

      const handleScroll = (event) => {
        const positionX = event.nativeEvent.contentOffset.x;
        const positionY = event.nativeEvent.contentOffset.y;
      };