Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to bottom in react?

Tags:

reactjs

I want to build a chat system and automatically scroll to the bottom when entering the window and when new messages come in. How do you automatically scroll to the bottom of a container in React?

like image 375
helsont Avatar asked Oct 05 '22 22:10

helsont


People also ask

How do you scrollTo the bottom of a page React?

To scroll to the bottom of a div in React: Add an element at the bottom of the div . Set a ref on the element at the bottom. When an event occurs, call the scrollIntoView() method on the ref object.

How do I change the scroll position in React?

To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.

How do I scrollTo the bottom of a div?

Use element. scroll() to Scroll to Bottom of Div in JavaScript. You can use element.


1 Answers

As Tushar mentioned, you can keep a dummy div at the bottom of your chat:

render () {
  return (
    <div>
      <div className="MessageContainer" >
        <div className="MessagesList">
          {this.renderMessages()}
        </div>
        <div style={{ float:"left", clear: "both" }}
             ref={(el) => { this.messagesEnd = el; }}>
        </div>
      </div>
    </div>
  );
}

and then scroll to it whenever your component is updated (i.e. state updated as new messages are added):

scrollToBottom = () => {
  this.messagesEnd.scrollIntoView({ behavior: "smooth" });
}

componentDidMount() {
  this.scrollToBottom();
}

componentDidUpdate() {
  this.scrollToBottom();
}

I'm using the standard Element.scrollIntoView method here.

like image 325
metakermit Avatar answered Oct 07 '22 12:10

metakermit