0

Setting the scrollTop property of a React node is not working.

I'm trying to restore the scroll position of a list when navigating to and from the page with the list.

Currently my code is the following:

  componentDidMount() {
    let prevScrollHeight = Number(localStorage.getItem('listHeight'));

    if (prevScrollHeight >= 0) {
      let listNode = ReactDOM.findDOMNode(this.refs.speakersList);
      listNode.scrollTop = prevScrollHeight;
    }
  }

The scroll height is successfully being stored in local storage. What's not working is: listNode.scrollTop = prevScrollHeight

Does anyone know how I can set the scroll position of a React node?

suntzu
  • 298
  • 2
  • 10
  • Instead of defining the refs as strings, you need to define them using ref callback syntax, check this: https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele/38093981#38093981 – Shubham Khatri Dec 19 '17 at 18:09
  • I don't see how this is relevant at all to the problem at hand (and the solution posted below). – suntzu Dec 19 '17 at 21:50

1 Answers1

0

Figured out the issue... For future reference if you have the same issue - the solution was to put the function that was setting the scrolltop in setTimeout. Seems like it has something to do with the JavaScript event loop, and setTimeout puts the function at the back of the queue.

Working code:

componentDidMount() {
  setTimeout(this.setScrollTop.bind(this))
}

setScrollTop() {
  let prevScrollHeight = Number(localStorage.getItem('listHeight'));

  if (prevScrollHeight >= 0) {
    let listNode = ReactDOM.findDOMNode(this.refs.speakersList);
    listNode.scrollTop = prevScrollHeight;
  }
}
suntzu
  • 298
  • 2
  • 10