14

I use the ListView's scrollToEnd, but it doesn't work, but it worked for scrollTo. What should I do to deal with it.

enter image description here

enter image description here

Eldelshell
  • 6,683
  • 7
  • 44
  • 63
Aaron_ls
  • 141
  • 1
  • 1
  • 4

5 Answers5

20

There is a workaround, wrap it in a setTimeout like so:

componentDidMount() {
  setTimeout(() => {
    this.refs.dateList.scrollToEnd();
  }, 50);
}
Samuel G. P.
  • 3,004
  • 2
  • 29
  • 36
13

Try this:

<ListView
    ref={ ( ref ) => this.scrollView = ref }
    onContentSizeChange={ () => {        
        this.scrollView.scrollToEnd( { animated: false } )
    } } >
</ListView>

document

Jian
  • 3,118
  • 2
  • 22
  • 36
Javid Jamae
  • 8,741
  • 4
  • 47
  • 62
1

For functional components, the equivalent is using useEffect like so:

useEffect(()=>{
    setTimeout(ref?.current.scrollToEnd());
},[yourArrayData])

Note, you don't need to set a duration for the setTimeout, this is because of Macrotasks in JavaScript, https://javascript.info/event-loop if you want to find out more

MorningLit
  • 36
  • 3
  • Note, with this solution, `yourArrayData` will cause the `useEffect` to call if it changes (if it in state) or has perceived to have changed since React does not run a deep check on objects in a dependency array [link](https://stackoverflow.com/questions/54095994/react-useeffect-comparing-objects), this answer is still a viable solution – Harrison May 22 '23 at 09:40
  • Yea I place the yourArrayData in the dependency array because it is equivalent to this other solution https://stackoverflow.com/a/46420586/13710770 Use an empty array if you want this other equivalent solution https://stackoverflow.com/a/46370418/13710770 – MorningLit May 25 '23 at 01:41
0

Rendering takes time so setTimeout() before scrolling to end will work. You can, however, use the onLayout() method.

export default MyComponent extends React.Component {
  constructor(props) {
    super(props)

    this.scrollToBottom = this.scrollToBottom.bind(this)
  }

  scrollToBottom() {
    this.refs.myView.scrollToEnd()
  }

  render() {
    return {
      <ListView
           onLayout={this.scrollToBottom}
           ref='myView'
           ...
      />
   }
 }

Note: ListView is now deprecated.

Chanoch
  • 563
  • 7
  • 16
0

This this worked for me.

<Content ref={c => (this.contentComponent = c)}>
....Any code
</Content >

This allows you to to use the scrollToPosition(0) function like

this.contentComponent._root.scrollToPosition(0);
kautikmistry
  • 686
  • 6
  • 10