How to scroll to bottom in react?

前端 未结 19 883
执笔经年
执笔经年 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 19:10

    1. Reference your messages container.

      { this.messagesContainer = el; }}> YOUR MESSAGES
    2. Find your messages container and make its scrollTop attribute equal scrollHeight:

      scrollToBottom = () => {
          const messagesContainer = ReactDOM.findDOMNode(this.messagesContainer);
          messagesContainer.scrollTop = messagesContainer.scrollHeight;
      };
      
    3. Evoke above method on componentDidMount and componentDidUpdate.

      componentDidMount() {
           this.scrollToBottom();
      }
      
      componentDidUpdate() {
           this.scrollToBottom();
      }
      

    This is how I am using this in my code:

     export default class StoryView extends Component {
    
        constructor(props) {
            super(props);
            this.scrollToBottom = this.scrollToBottom.bind(this);
        }
    
        scrollToBottom = () => {
            const messagesContainer = ReactDOM.findDOMNode(this.messagesContainer);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        };
    
        componentDidMount() {
            this.scrollToBottom();
        }
    
        componentDidUpdate() {
            this.scrollToBottom();
        }
    
        render() {
            return (
                
    { this.messagesContainer = el; }} className="chat"> { this.props.messages.map(function (message, i) { return (
    {message.body}
    ); }, this) }
    ); } }

提交回复
热议问题