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?
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.
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.
Use element. scroll() to Scroll to Bottom of Div in JavaScript. You can use element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With