lizhijia1989
lizhijia1989

Reputation: 31

react-native SectionList How to scrollToTop by using scrollToLocation?

I can only scrollTo items or itemTitle by using this func, but I can't find a way to scrollToTop. There are 5 params I can use below.

this.sectionListRef.scrollToLocation({
  sectionIndex: 0,
  itemIndex: -1,
  viewPosition: 1,
  viewOffset: 0,
  animated: true,
});

Thanks.

Upvotes: 0

Views: 2502

Answers (2)

lizhijia1989
lizhijia1989

Reputation: 31

I can't find any api or func to scrollToTop by using SectionList. I can only calculate the viewOffset to scrollToTop.

this.sectionHeaderHeight is the height of the sectionListHeader (e.native.layout.height)

this.sectionListRef.scrollToLocation({
  sectionIndex: 0,
  itemIndex: 0,
  viewPosition: 0,
  viewOffset: this.sectionHeaderHeight,
  animated: true,
});

Upvotes: 3

LordKiz
LordKiz

Reputation: 643

add a function to scroll to the top:

scrollToTop() {
    this.scroll.scrollTo({x:0, y:0, animated: true})
}

In your ScrollView add:

<ScrollView
    ref={(f) => { this.scroll = f }}
>
.......
</ScrollView>

There after you can add maybe a floating button that calls scrollToTop function. Or you can even use it after setting state or whatever. eg:

setSomeState(something) {
    this.setState({ something }, () => this.scroll.scrollTo({x:0, y:0, animated: true }));
}

Upvotes: -1

Related Questions