Scroll Bottom with React


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:

<div ref={(node) => { this.node = node; }}>
<Comments />
</div>

In componentWillUpdate we use the ref to set a boolean shouldScrollBottom using scrollTop and offsetHeight

componentWillUpdate() {
const node = this.node;
this.shouldScrollBottom = node.scrollTop +
node.offsetHeight === node.scrollHeight;
}

In componentDidUpdate we use the bool shouldScrollBottom to scroll to the bottom.

componentWillUpdate() {
const node = this.node;
this.shouldScrollBottom = node.scrollTop
+ node.offsetHeight === node.scrollHeight;
}

Everytime the div including the <Comments /> component changes in size (for example new comment) it will autoscroll to the bottom.

Related Posts

Moment.js - Reduce Webpack Bundle Size

How to reduce the packaged webpack bundle size of moment.js

Javascript condition & 0 value

How to prevent headaches with 0 values and Javascript conditions