0

I am trying to scroll a list of messages automatically to the bottom whenever the list is updated. This is my code:

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import Message from "../components/message";
import MessageForm from "../containers/message_form";

import { fetchMessages } from "../actions";

class MessageList extends Component {
  componentWillMount() {
    this.fetchMessages();
  }

  componentDidMount() {
    this.refresher = setInterval(this.fetchMessages, 5000);
  }

  componentDidUpdate() {
    this.list.scrollTop = this.list.scrollHeight;
  }

  componentWillUnmount() {
    clearInterval(this.refresher);
  }

  fetchMessages = () => {
    this.props.fetchMessages(this.props.selectedChannel);
  };

  render() {
    return (
      <div>
        <div>
          <span>Channel #{this.props.selectedChannel}</span>
        </div>
        <div
          ref={(list) => {
            this.list = list;
          }}
        >
          {this.props.messages.map((message) => {
            return <Message key={message.id} message={message} />;
          })}
        </div>
        <MessageForm />
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    messages: state.messages,
    selectedChannel: state.selectedChannel,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchMessages }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(MessageList);

Whenever a message is submitted via the form or the list is updated by the created function, it does not scroll automatically. I referenced the affected list component but it doesn't seem to be right. Do you have any suggestions?

Davide
  • 17
  • 5

1 Answers1

1

You can create a dummy div at the end of your component and use scrollIntoView to scrool to the bottom.

check this for the refrence How to scroll to bottom in react?

please give a thumbs up if i halped you.

  • Instead of answering and basically linking to the *actual* answer perhaps it is better to flag the post as a duplicate, or if you are unsure, leave as a comment your comment and the link to the other SO post/answer. – Drew Reese May 24 '21 at 08:29
  • This answer is probably OK, but could you provide an example in code, so that is is easier to understand. – chrwahl May 24 '21 at 08:29
  • You were right. Actually was the same issue from the other answer. Thanks – Davide May 24 '21 at 09:01