I am working on developing a chat feature, but I am facing an issue where the new message does not appear on the screen after a certain number of messages. I want the messages to overflow so that users can scroll down to view them, but only a few messages are displayed and nothing happens after that point. The previous messages remain static on the screen. I am using React along with Socket.io for this project. Here is the code snippet:
const [messagesAndAuthors, setMessagesAndAuthors] = useState<any>([]);
useEffect(() => {
socket.on('receivedMessage', (newMessage:{}) => {
messagesAndAuthors([...messagesAndAuthors, newMessage])
});
})
function sendingMessages(e : FormEvent) {
e.preventDefault();
if(message.trim()) {
const messageObject = {
userName,
message,
roomId
};
socket.emit('sendMessage', messageObject);
}
setMessage('');
}
----------------------------BACK-END(SOCKET.IO):
socketInfo.on('sendMessage', (data:any) => {
socketInfo.broadcast.emit('receivedMessage', data);
});
.chat-container {
margin: 0.5rem;
display: flex;
flex-direction: column;
align-items: center;
font: 400 1rem 'Sulphur Point';
background-color: #254441;
padding: 2rem 0;
border-radius: 2rem;
justify-content: space-between;
text-align: center;
max-height: 77.5vh;
overflow: auto;
}
.chat-container h1 {
background-color: #ff6f59;
padding: 0.2rem 4rem;
border-radius: 2rem;
text-align: center;
align-items: center;
justify-content: center;
margin-bottom: 1rem;
}
.messages-container {
text-align: start;
background-color: #254441;
border-radius: 2rem;
height: 90%;
margin-bottom: 0.5rem;
overflow: auto;
}
.messages-mine-style {
width: 15rem;
border: transparent;
border-radius: 1.5rem;
margin-top: 2rem;
text-decoration: none;
text-align: start;
list-style: none;
font: 700 1.4rem 'Sulphur Point';
padding: 0.2rem 0.6rem;
margin: 1rem 0;
}
.messages-mine-style li{
margin-left: 1rem;
}
.messages-mine-style li+li {
font: 400 1.4rem 'Sulphur Point';
}
.chat-container input {
background-color: #ff6f59;
padding: 1rem 4rem;
border-radius: 2rem;
text-align: center;
font: 700 1.2rem 'Sulphur Point';
outline: none;
border: transparent;
}
.chat-container input::placeholder {
color: #254441;
}
<form onSubmit={sendingMessages} className="chat-container">
<h1>Chat</h1>
<div className="messages-container">
{messagesAndAuthors.map((messageWithTheAuthor:any) => {
return (
<>
<ul className="messages-mine-style">
<li key={messageWithTheAuthor.author}>{messageWithTheAuthor.author}: </li>
<li>{messageWithTheAuthor.message}</li>
</ul>
</>
)
})}
</div>
<input value={message} onChange={(e) => {setMessage(e.target.value)}} type="text" placeholder="Type your message here"/>
</form>