HiveBrain v1.2.0
Get Started
← Back to all entries
snippetreactCritical

How to scroll to bottom in react?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
scrollreacthowbottom

Problem

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?

Solution

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

render () {
return (



{this.renderMessages()}

{ this.messagesEnd = el; }}>



);
}


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.

Context

Stack Overflow Q#37620694, score: 362

Revisions (0)

No revisions yet.