I am working on a chat app, everytime I put a message I need to scroll to the bottom in order to see the new messages. So, as in a regular chat, I need to provide the functionality that the user may be able to see the last messages without manually scrolling to the bottom.
I am using React, is there a css way? or can you tell me the best way to do that ?
let me show you some code
this is the main component
render () {
let messages = this.props.chatMessages.map((message) => {
return <ChatItem info={message.info} me={message.me} player={message.player} message={message.message} />;
});
let chatForm;
if (this.props.mode === 'player') {
chatForm = <ChatForm onAddMessage={this.addMessage} />;
}
return <div className="Chat">
<ul className="Chat__messages">{messages}</ul>
<hr />
<div>{chatForm}</div>
</div>;
}
here are the ChatItem
and ChatForm
components
render () {
let item;
const { message, player, me, info } = this.props;
if (info) {
item = <li><em>{message}</em></li>;
}
else if (me) {
item = <li><strong>Me: {message}</strong></li>;
}
else {
item = <li><strong>{player}:</strong> {message}</li>;
}
return item;
}
render () {
return <div className="ChatForm">
<input
className="ChatForm__input"
placeholder="Your message..."
ref="newMessage"
onKeyDown={this.onKeyDown}
autofocus="true" />
</div>;
}
ADDING INFO
I need something like this http://codepen.io/TimPietrusky/pen/ylkFs
Look at this part
// Scroll the latest line of output
output.scrollTop(
output[0].scrollHeight - output.height()
);
how should I adapt it to my code on React ?
One way to do it is to compare current and previous/next props in a lifecycle event such as componentDidUpdate
and scroll to bottom if a new message was added. For example:
componentDidUpdate(prevProps) {
// Check if new message was added, for example:
if (this.props.messages.length === prevProps.messages.length + 1) {
// Scroll to bottom
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.