How to scroll to bottom in react?

前端 未结 19 915
执笔经年
执笔经年 2020-11-28 18:27

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

19条回答
  •  感动是毒
    2020-11-28 18:47

    thank you 'metakermit' for his good answer, but I think we can make it a bit better, for scroll to bottom, we should use this:

    scrollToBottom = () => {
       this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
    }
    

    but if you want to scroll top, you should use this:

    scrollToTop = () => {
       this.messagesEnd.scrollIntoView({ behavior: "smooth", block: "start", inline: "nearest" });
    }   
    

    and this codes are common:

    componentDidMount() {
      this.scrollToBottom();
    }
    
    componentDidUpdate() {
      this.scrollToBottom();
    }
    
    
    render () {
      return (
        
    {this.renderMessages()}
    { this.messagesEnd = el; }}>
    ); }

提交回复
热议问题