Dave
Dave

Reputation: 425

How can I keep position on ScrollView or ListView?

When you use ScrollView or ListView in your ReactNative app and some new data came in, the default behavior of them is to keep the position in the Scroll component. Which means if the new data of height 20 came in when you're at the middle of the ScrollView, on-screen items will slide by 20 and sometimes it will go off the screen.

Is there any way to keep/track the position? for example, if the new data of height 20 came in, the position automatically adjust the position by 20 so that current on screen items keep on the screen. Thanks in advance.

Upvotes: 6

Views: 7528

Answers (2)

Idan
Idan

Reputation: 4023

More elegant sulotion:

<ScrollView
    ref={(ref => this.scrollViewRef = ref)}
    onScroll={event => { this.yOffset = event.nativeEvent.contentOffset.y }}
    onContentSizeChange={(contentWidth, contentHeight) => { this.scrollViewRef.scrollTo({ x: 0, y: this.yOffset, animated: false }) }}>

Upvotes: 1

Antoine
Antoine

Reputation: 5692

I have a working solution, although it's not very smooth, it does the job:

handleScroll = (event) => {
  this.scroll = event.nativeEvent.contentOffset.y
  if (this.ready && this.scroll < SCROLL_TRIGGER) {
    // load more stuff here
  }
}

handleSize = (width, height) => {
  if (this.scroll) {
    const position = this.scroll + height - this.height
    this.refs.sv.scrollTo({x: 0, y: position, animated: false})
  }
  this.height = height
}

// render:

<ScrollView ref="sv"
  scrollEventThrottle={16}
  onScroll={this.handleScroll}
  onContentSizeChange={this.handleSize}
>
  {content}
</ScrollView>

If someone made something smoother, let us know!

Upvotes: 4

Related Questions