Keep scroll-y after rerender

Viewed 16643

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?

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.

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.

Related