React: Auto scroll when overflow

React: Auto scroll when overflow

I recently had an issue with an React app, in which contents was added to the bottom of an area – a <div> element with the CSS property overflow: scroll; set – on the screen. I wanted the app to automatically scroll to the latest element.

I found this post on StackOverflow which seemed to be what I needed, and while the auto scroll feature did work it was kind of our of sync with the content. I figured the issue had something to do with React component’s life cycle, causing the content area’s dimension to be calculated after the initial rendering. Placing the code that sets the scrollbar’s position in componentDidUpdate function, fixed the “sync” issue mentioned:

class MyComponent extends React.Component {

  componentDidUpdate() {
    var scrollable_area = document.getElementById("scrollable_area");
    scrollable_area.scrollTop = scrollable_area.scrollHeight;

  render() {

    return (
      <div id="scrollable_area">
        /* Contents */

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: