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
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.