1

I am using react-native scrollview to slide my imageBackground.

I am using pagingEnabled to swipe the images. But is there a way I could get number of the index when ever I swipe?

I am using the scroll view like the code below. Adding pagingEnabled will make the scrollview work like a swiper but I don't know how to get the index.

<ScrollView horizontal={true} pagingEnabled={true}>
            {this.createScrollImageSources(this.state.image)}
</ScrollView>
Tim
  • 10,459
  • 4
  • 36
  • 47
kirimi
  • 1,370
  • 4
  • 32
  • 57
  • 1
    https://stackoverflow.com/questions/38799702/how-to-show-current-page-num-of-paging-scrollview does this help you? – Andus Jan 10 '20 at 18:28

2 Answers2

6

You could make use of the onScroll method together with the Dimensions module to calculate the currentScreenIndex.

Example:

render

  <View style={styles.container}>
   <ScrollView pagingEnabled horizontal style={{flex: 1}} onScroll={(e)=>this.handleOnScroll(e)} scrollEventThrottle={5}>
     <View style={{width: SCREEN_WIDTH, backgroundColor: 'yellow'}} />
     <View style={{width: SCREEN_WIDTH, backgroundColor: 'red'}} />
     <View style={{width: SCREEN_WIDTH, backgroundColor: 'green'}} />
   </ScrollView>
  </View>

handleOnScroll

  handleOnScroll(event){
    //calculate screenIndex by contentOffset and screen width
    console.log('currentScreenIndex', parseInt(event.nativeEvent.contentOffset.x/Dimensions.get('window').width));
  }

Working Demo

https://snack.expo.io/HyxzFr2HxU

Tim
  • 10,459
  • 4
  • 36
  • 47
0

What I did was to use the onScroll prop to check the current offset of the horizontal scrollview. Then compare the current offset with your device width.

Try:

<ScrollView onScroll={this.handleScroll} />

And then:

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