kirimi
kirimi

Reputation: 1400

How to get scrollview index

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>

Upvotes: 1

Views: 8116

Answers (2)

Tim
Tim

Reputation: 10709

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

Upvotes: 8

user4293315
user4293315

Reputation:

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);
},

Upvotes: 0

Related Questions