How to scroll to bottom in react?

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

    You can use refs to keep track of the components.

    If you know of a way to set the ref of one individual component (the last one), please post!

    Here's what I found worked for me:

    class ChatContainer extends React.Component {
      render() {
        const {
          messages
        } = this.props;
    
        var messageBubbles = messages.map((message, idx) => (
           this['_div' + idx] = ref}
          />
        ));
    
        return (
          
    {messageBubbles}
    ); } componentDidMount() { this.handleResize(); // Scroll to the bottom on initialization var len = this.props.messages.length - 1; const node = ReactDOM.findDOMNode(this['_div' + len]); if (node) { node.scrollIntoView(); } } componentDidUpdate() { // Scroll as new elements come along var len = this.props.messages.length - 1; const node = ReactDOM.findDOMNode(this['_div' + len]); if (node) { node.scrollIntoView(); } } }

提交回复
热议问题