I create a chat. I have sent and received messages. On the left side (color red are the messages I have received), on the right side the messages I have sent (color cyan). However, these messages are not in the order they should be. How to set up chat messages using css rules based on time and messages received and sent? The order of messages should be as shown in the attached photo. The message Ok. And you?
. Should be in the place marked in black (3), and it comes first.
//ChatUser.js
import React, { useState, useRef} from 'react';
import './Chat.css';
const ChatUser = () => {
const [values, setValues] = useState({
messages: [
{
_id: '610be2c',
text: 'Hello. How are you???',
sender: '6003123',
receiver: '608ffae',
createdAt: '2021-12-26T17:58:00.876 00:00'
},
{
_id: '610be2d',
text: '???',
sender: '6003123',
receiver: '608ffae',
createdAt: '2021-12-26T17:58:10.494 00:00'
},
{
_id: '610be2d890',
text: "Ok. and you?",
sender: '608ffae',
receiver: '6003123',
createdAt: '2021-12-26T17:58:10.494 00:00'
},
{
_id: '610be2dtyu',
text: "Tell me!!!",
sender: '6003123',
receiver: '608ffae',
createdAt: '2022-01-01T18:02:36.766 00:00'
}
]
});
return (
<>
<ul className="containerMessages">
{messages && messages.length > 0 ? messages.map( message => {
return <li className = {message.sender == "600" ? 'left' : 'right'} key={message['_id']}>
{message.text}
</li>;
}) : null}
</ul>
<div>
<Button type="primary" htmlType="submit">
Send
</Button>
</div>
</>
);
};
//Chat.css
.containerMessages {
padding: 0;
display: flex;
/* column reverse to have chat-style message ordering*/
flex-direction: column-reverse;
list-style-type: none;
}
.left {
background: cyan;
/* use align-self */
align-self: flex-end;
border: 1px solid gray;
border-radius: 5px;
margin: 7px;
margin-left: 0;
padding: 5px;
width: 60%;
}
.right {
background: pink;
border: 1px solid gray;
border-radius: 5px;
margin: 7px;
margin-right: 0;
padding: 5px;
width: 60%;
}
CodePudding user response:
You can't order an array by its object values only by css, instead you have to order it with js before you map it.
array.sort(function(a,b){
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});