Reputation: 2947
My use case is to restore the scroll position of a <div>
inside a React component, when the user navigates back to the respective (parent) route. I track the scroll position of the <div>
using onScroll
. My idea is to save the scroll position in the history state. It is possible to call history.replace()
with an updated state object in the scroll event handler, but the performance is poor (I assume history.replace()
forces the component to re-render).
I also tried to call history.replace()
in componentWillUnmount()
(while saving the scroll position as an instance attribute of the component). That however, is too late since history.location
has already been changed to the new location.
The same is true for a history listener (history.listen()
).
Are there alternative approaches to implement the scroll position restoring?
Upvotes: 0
Views: 384
Reputation: 46
From your description it appears you may be battling with React and their use of the history API.
An alternative solution may be to store solely an array position in history, which would only require a single replace, and manage the updates to scroll values themselves in an array held within (for example) localStorage.
Hope this is helpful.
Upvotes: 1