So I have a React application, and I want to scroll to the bottom of a div.
componentDidMount() {
this.pullMessages();
this.scrollToBottom();
}
pullMessages() {
var api = new API(this.props.keycloak);
var merchant_id = this.props.location.pathname.substr(this.props.location.pathname.lastIndexOf('/') + 1);
api.get("merchantMessages", { "repl_str": merchant_id }).then(
response => this.loadMessages(response.data)
).catch(function (error) {
console.log(error);
})
}
loadMessages(data) {
var count = 0;
var messagevals = [];
data.reverse().forEach(function (obj) {
messagevals.push(generateMessage(obj, count, {}));
count++;
});
this.setState({ messages: messagevals });
this.setState({ isLoading: false });
}
scrollToBottom = () => {
// Using this method because the reference didn't work
var bottomele = document.getElementById("bottom-scroll");
if (bottomele !== null) {
bottomele.scrollIntoView();
}
}
render() {
if (this.state.isLoading) {
return (<Loading />)
}
else {
return (
<div>
<div id="messages-container">
<div id="messages">
{ this.state.messages.map((message, index) =>
<div className={ "message " + message.position} key={index}>{message.text}</div>
}
<div className="bottom-scroll" id="bottom-scroll" ref={(el)=> { this.messagesEndRef = el; }}>
</div>
</div>
</div>
</div>
....
It is populated via an API call (and a loading modal is shown until this API call fills an array in state)
My problem is that I want to scroll to the bottom once the messages div is populated.
My issue is that my scroll to the bottom code seems to be executing before the messages are filled in, and so no scrolling happens.
How do I make sure to scroll only when my messages are populated and rendered? I've considered putting it in componentDidUpdate(), but the problem with that is I only want this scroll action to happen on first load, and then on message send.