One example could be to have a react component to render comments with CSS Scrolling. When adding a new comment it should autoscroll to the bottom to always view the last comment.
To solve this we are going to use React Lifecycle methods componentWillUpdate
and componentDidUpdate
.
First we need to add a reference which we can access in the lifecycle methods:
In componentWillUpdate
we use the ref to set a boolean shouldScrollBottom
using scrollTop and offsetHeight
In componentDidUpdate
we use the bool shouldScrollBottom
to scroll to the bottom.
Everytime the div including the <Comments />
component changes in size (for example new comment) it will autoscroll to the bottom.