I'm writing a chat application using reactjs and I am trying to figure out how to change the focus to the latest message every time a new message is added to the array. My react chat window looks like this:
<ChatHeader />
<Messages datas={this.state.datas} />
<ChatFooter sendMessage={this.sendMessage} />
and my Messages component looks like this:
var Messages = React.createClass({
render: function() {
// Loop through the list of messages and create array of Row components
var Rows = this.props.datas.map(function(data) {
return (
<Row username={data.username} message={data.message} />
)
});
return (
{Rows}
);
}
});
So basically every time my main chat window rerenders, I want messages to be displayed with the list scrolled all the way down (showing the most recent messages - or the last few things in the Rows array). I found a few questions about shifting focus like this one here but when I try shifting focus to messages it brings me to the top of the list. Ideally I'd like to add something like this:
var Rows = this.props.datas.map(function(data) {
return (
<Row username={data.username} message={data.message} />
)
});
// Rows[Rows.length - 1].ref = "last";
so I can then focus on the last element in the array but I haven't been able to find a way to set references like this. All the ways I've seen show setting the reference inside the tag. Does a way to assign references like this exist?
I also thought about giving each row a unique id number and incrementing that number for each new message, ,keeping track of the largest number and then using that to reference the last element but it seems like there must be a better way. What is the best way to accomplish this?