Shashika Virajh
Shashika Virajh

Reputation: 9457

ScrollToIndex in React-Native

In my application, I want to use scrollToIndex() which is a method of the FlatList component.

 render() {
    let { posts, featuredWorkouts, mainFeedIsLoading } = this.props;
    let mainFeed = <SwiperContainer featuredWorkouts={featuredWorkouts} />;

    let mainFeedData = (
      <View>
        <View style={{ marginBottom: 5 }}>
          <SwiperContainer featuredWorkouts={featuredWorkouts} />
        </View>

        <FlatList
          data={posts}
          scrollToIndex={5}
          extraData={[posts, mainFeedIsLoading]}
          renderItem={item => this.renderPost(item)}
          keyExtractor={item => item.shareId}
        />
      </View>
    );

    if (mainFeedIsLoading) {
      mainFeedData = (
        <View style={styles.screenLoader}>
          <ScreenLoader color="lightblue" size="large" />
        </View>
      );
    }

    return (
      <View>
        <ScrollView>{mainFeedData}</ScrollView>
      </View>
    );
  }

As an example, when the page loads, I want to go to the 10th index. How can I achieve this? I tried the scrollToIndex() and it did not work.

Upvotes: 0

Views: 1570

Answers (2)

niz
niz

Reputation: 57

Well in my case I have to do this to make scrolltoindex work properly,

1.add reference to flatlist:

`
ref={ref => {
this.flatListRef = ref;
}}
`

2. Call scrollToIndex() with timeout:

`
setTimeout(() => {
      this.flatListRef.scrollToIndex({
    animated: true,
    index: this.state.pressedIndex
      });
    }, 500);
`

3. then call function again inside flatlist

 onScrollToIndexFailed={() => 
 {
  this.scrollToIndex();

}

}

Upvotes: 0

Amin Noura
Amin Noura

Reputation: 317

you have to add ref to your flat list.

ref={(ref) => { this.list = ref; }}

Also you have to add to scroll index to your componentdidmount.

componentDidMount() {
    this.list.scrollToIndex({animated: true, index: tempIndex, viewOffset:0,viewPosition:0});
}

Also you can use:

initialScrollIndex

Upvotes: 1

Related Questions