Search code examples
reactjsdomscrolltopreact-dom

React - scrolling to the bottom of a flex container without scrolling the whole page


I'm using react and trying to build a facebook like chat - where the right column scrolls down and has a list of threads, and the middle column had the thread content and scrolls bottom up.

I have it all setup using flex, but am stuck on getting the middle column to scroll to the bottom by default (since I want to see the latest chat message). Here is the snippet for the actual container (I'm using React bootstrap):

 <Row  >
    <Col ref={ (node) => { this.cont = node }}>
                                {this._buildThread()};
   </Col>
</Row>

and here is the snippet for my ComponentDidMount:

componentDidMount() {
    MessageStore.addChangeListener(this._onChange);
    MessageService.getThread(this.props.id, 1000, 1, false);

    this.cont.scrollTop = this.cont.scrollHeight;

}

Where cont is the ref for the container div that holds my messages. Yet nothing happens - it doesn't scroll, and if I look at node.scrollTop after setting it, it remains at 0 - seems immutable. Any help would be much appreciated. Thanks!


Solution

  • Not sure about the details of your CSS, but I just had a similar-looking issue. The solution in my case was to make sure that the element itself would scroll and not its container:

    .containerIWantToScroll {
        overflow-y: auto;
    }
    

    If the element's container expands to fit the element, then that element will not scroll, thus its scrollTop value is always zero.