3

I am using react-native-swiper-flatlist , I want to scroll forward to some index by tapping button but no clue how to do it. Although I am very beginner to react native development.

I have searched alot but nothing helps, I get an error of undefined is not an object this2.swiper.scrollToIndex'

render() {
return (
  <View style={styles.container}>
    <SwiperFlatList
      ref={swiper => {
        this.swiper = swiper;
      }}
      data={[
        { key: "a" },
        { key: "b" },
        { key: "c" },
        { key: "d" },
        { key: "e" }
      ]}
      index={0}
      renderItem={({ item, index }) => (
        <View>
          <Image
            style={styles.child}
            source={require("../../assets/advertisementtwo.png")}
          />
          <Image
            style={styles.child}
            source={require("../../assets/advertisementtwo.png")}
          />
          <Image
            style={styles.child}
            source={require("../../assets/advertisementtwo.png")}
          />
          <Image
            style={styles.child}
            source={require("../../assets/advertisementtwo.png")}
          />
          <Button
            title={"Next"}
            onPress={this.swiper.scrollToIndex(1, true)}
            style={{ backgroundColor: "white" }}
          />
        </View>
      )}
    />
  </View>
);

}

Should swipe on button click

Here is the screenshot of the error I am getting

Zoe
  • 27,060
  • 21
  • 118
  • 148
Talha Asif
  • 35
  • 4

2 Answers2

3

Try adding ref='swiper' as a SwiperFlatList prop,

Example

<SwiperFlatList ref='swiper'/>

this.refs.swiper._scrollToIndex(2)

Harshal Valanda
  • 5,331
  • 26
  • 63
  • I have figured out the problem "onPress={this.swiper.scrollToIndex(3)}" should be replaced by onPress={() => { this.refs.swiper._scrollToIndex(3) }} thanks – Talha Asif Jan 17 '19 at 10:34
  • 1
    You need to set `this.refs.swiper.scrollToIndex(2)` and declare reference as example – Harshal Valanda Jan 17 '19 at 10:36
0

For those who are using React hook instead of class, you can do sth like that to utilise the scrollToIndex function

//First,  make a ref for storing the swiper instance inside your swiper compoent
const swiperRef = useRef<any>({});

//Second, store the reference
<SwiperFlatList
    ref={(component) => { swiperRef.current._swiper = component; }}
>

//Later on, you can call the function like this
swiperRef.current._swiper.scrollToIndex({index: 2})
tcf01
  • 1,699
  • 1
  • 9
  • 24