damingzi
damingzi

Reputation: 716

How can I align my chat entries to the right in the chat room?

I have an react chat app, attached screenshot below. All entries with an orange vertical bar are input from myself. What I want to achieve is to put all my chat to the right side of the chat room. Please let me know what changes in message_self can achieve it. Thanks! enter image description here

Below is the code to output all chat history:

  <React.Fragment>
    <Segment>
      <Comment.Group className="messages">
        this.displayMessages(messages)
    </Segment>
  </React.Fragment>

The definition of displayMessages is below:

displayMessages = messages =>
    messages.length > 0 &&
    messages.map(message => (
      <Message
        key={message.timestamp}
        message={message}
        user={this.state.user}
      />
    ));

And here is the code for the Message component:

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image") && !message.hasOwnProperty("content");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (
        <Comment.Text>{message.content}</Comment.Text>
      )}
    </Comment.Content>
  </Comment>
);

In index.css, the message__self is like:

.message__self {
  border-left: 2px solid orange;
  padding-left: 8px;
}

Upvotes: 0

Views: 1529

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

I think all you need to do is flip the contents for the Comment block.

So for your Comment component at the top, you need some logic to determine what className to use.If the current-user owns this comment, then reverse the original layout.

const Message = ({ message, user }) => (
  <Comment className={message.user.id === user.uid ? reverse : ""}>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (
        <Comment.Text>{message.content}</Comment.Text>
      )}
    </Comment.Content>
  </Comment>
);

Then in your CSS file, define a class for reverse

.reverse {
  display: flex;
  flex-direction: row-reverse;
}

Upvotes: 2

Related Questions