Search code examples
reactjsanimationscrollautomessenger

How to auto scroll top to bottom in react for messenger?


How to auto scroll top to bottom in react for messenger or others?

class MessageBox extends Component {

  componentDidMount() {
    this.scrollToBottom();
  }

  componentDidUpdate() {
    this.scrollToBottom();
  }


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

  render() {
      return (
        <div className="yourClass">
            <div className="chat-textarea-box">
                <MessageBox />
            </div>
            <div ref={(el) => { this.messagesEnd = el; }}></div>
        </div>
      )
    }
}

Please provide me better solutions


Solution

  • u can set flex direction to column-reverse and it will automatically be your bottom so you dont need to scroll on every new msg,also with this way you need to reverse your array of messages