JK9
JK9

Reputation: 380

FlatList scroll to top while FlatList in child component

I am quite new to react native and would like to ask how to scroll to top when tap on button in a FlatList. However, in my case, the FlatList is inside a child component which I don't know how to pass the ref around.

I have tried createRef() in the parent component and pass it down to child component where the FlatList in. However, still getting error like _this.flatListRef.scrollToIndex is not a function

Here is what I have tried so far: link expo

Upvotes: 0

Views: 2886

Answers (1)

Jebin Benny
Jebin Benny

Reputation: 951

Try the following,

 _didTapOnButton=()=>{
   setTimeout(() => {
    if (this.timerFlatlistRef)
      this.timerFlatlistRef.scrollToIndex({
        animated: true,
        index: 0,
      });
  }, 1000);
 }

 _getItemLayout = (data, index) => ({
    length: 24,
    offset: 100 * index,
    index
 });

_renderItems = ({ item, index }) => {
 ...
 ...
}

...
<FlatList
     ref={ref => (this.timerFlatlistRef = ref)}
     style={{ flex: 1, paddingTop: 10 }}
     data={dayHours}
     getItemLayout={this._getItemLayout}
     renderItem={this._renderItems}
     keyExtractor={(item, index) => String(index)}
     extraData={this.state}
/>
...

Upvotes: 1

Related Questions