Reputation:
I have a Chat
component with some methods and it has piece of code that generate messages sent by two people one below another.
render() {
...
<div id="window" className="window">
<div className="messages">
{this._renderMessages()}
</div>
</div>
...
}
The method only generates more div
with varying styles depending who sent the message, and window
has a vertical overflow
set to auto
but it is always at the top.
.window {
border-radius: 10px;
max-height: 264px;
overflow: auto;
overflow-x: hidden;
}
My attempts were to take the window
element by its ID and set its scrollTop
of 0 to the value of scrollHigh
, but it isn't working. It is making no difference.
const window = document.getElementById("window");
window.scrollTop = window.scrollHeight;
I tried placing the code above in componentWillMount
and componentWillReceiveProps
but none worked. I also attempted to set a ref
on the div
and access it with this.refs.window
but it did not work either, despite showing the values. What am I doing wrong when attempting to assign the value?
Upvotes: 0
Views: 27
Reputation: 195971
You would need to run the scroll-to-bottom code after every update (and on initial render). The life-cycle methods for these actions are componentDidMount
(for initial render) and componentDidUpdate
(for subsequent updates).
So something like
class YourComponent extends ...{
constructor(props){
super(props);
this.window = React.createRef();
}
scrollToBottom(){
const element = this.window.current;
element.scrollTop = element.scrollHeight;
}
componentDidMount(){
this.scrollToBottom()
}
componentDidUpdate(){
this.scrollToBottom();
}
render() {
...
<div id="window" className="window" ref={this.window}>
<div className="messages">
{this._renderMessages()}
</div>
</div>
...
}
}
Demo at https://codesandbox.io/s/y3qvv04l7j
Keep in mind that you might want to do some checks before scrolling to bottom after each update, if for example you want to allow scrolling until new data are displayed etc..
Upvotes: 0