Reputation: 59
I am going back to programming after some time. I wrote chatApp once. Now I want to change something there. For now, new messages on chat shows on the top of messages list. I want make it on the bottom. I guess that I have to do something with state update. Please show me where it was.
class App extends Component {
constructor(props) {
super(props);
this.state = {users: [], messages: [], text: '', name: ''};
}
componentDidMount() {
socket.on('message', message => this.messageReceive(message));
socket.on('update', ({users}) => this.chatUpdate(users));
}
messageReceive(message) {
const messages = [message, ...this.state.messages];
this.setState({messages});
}
chatUpdate(users) {
this.setState({users});
}
handleMessageSubmit(message) {
const messages = [message, ...this.state.messages];
this.setState({messages});
socket.emit('message', message);
}
handleUserSubmit(name) {
this.setState({name});
socket.emit('join', name);
}
render() {
return this.state.name !== '' ? (
this.renderLayout()
) : this.renderUserForm()
}
renderLayout() {
return (
<div className={styles.App}>
<div className={styles.AppHeader}>
<div className={styles.AppTitle}>
ChatApp
</div>
<div className={styles.AppRoom}>
App room
</div>
</div>
<div className={styles.AppBody}>
<UsersList
users={this.state.users}
/>
<div className={styles.MessageWrapper}>
<MessageList
messages={this.state.messages}
/>
<MessageForm
onMessageSubmit={message => this.handleMessageSubmit(message)}
name={this.state.name}
/>
</div>
</div>
</div>
);
}
Upvotes: 4
Views: 827
Reputation: 8632
just change this handler.
messageReceive(message) {
const messages = [message, ...this.state.messages];
this.setState({messages});
}
in order to append the new message to the bottom.
messageReceive(message) {
const messages = [...this.state.messages, message];
this.setState({messages});
}
Upvotes: 3
Reputation: 17654
you can reverse the array of messages and pass it to the MessagesList
<MessageList
messages={this.state.messages.reverse()}
/>
Upvotes: 1