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?