Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep scroll-y after rerender

I have dropdown list with a lot of checkboxes, so this container has scroll. But when i click on any checkbox - it selects\deselects itself and then state changes.

So the problem is that after rerendering this container is back to the top. Is it possible to keep container's scroll after rendering without saving it to the state?

like image 850
Vladimir Novopashin Avatar asked Oct 29 '18 11:10

Vladimir Novopashin


People also ask

How do you keep the scroll position in React?

By default you can set the value of scrollPosition is 0 . Here I have used the sessionStorage to maintain the scroll position for demo purpose. You can also use the context API or redux store to manage it.

How can I retain the scroll position of a scrollable area when pressing back button?

You can try $("div#element"). load(function() {}) and place the element outside the document ready handler. Also, if a user scroll down the page, then leave the page, and go back to the page again, it should be a new start for him so it should start at the top. But now it also remembers the previous position.

How do you keep the scroll position using Flatlist when navigating back in React native?

In Flatlist set scrollsToTop={false} this will retain position when you navigate back from detail screen.


2 Answers

You can save the "snapshot" of the scroll position before the commit phase.

getSnapshotBeforeUpdate() shows kind of what you are looking for.

The documentation example saves the current scroll position within getSnapshotBeforeUpdate lifecycle method and then use the snapshot value passed to componentDidUpdate(prevProps, prevState, snapshot) as the last argument to restore the scroll position.

It doesn't require creating a state to save the scroll position as you requested.

like image 133
dance2die Avatar answered Oct 17 '22 16:10

dance2die


It's happening because you are re-rendering the complete list of the checkboxes.

There are 2 possible approaches:

  1. Re-render only relevant checkbox
  2. Save the scroll position of the container and update it once component is re-rendered.

Unfortunately, you haven't added any code examples, so can't share the code changes.

like image 1
Rahul Gandhi Avatar answered Oct 17 '22 18:10

Rahul Gandhi