Search code examples
reactjsreact-nativealignmentmessageboxreact-native-gifted-chat

React gifted chat message alignment


I cannot get messages from two users to align on the left and right side, while pulling them from state. They all go on the left side. If i try to post a new message, that message goes on the right side as expected, but not while pulling them from state.

Example code

    import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { GiftedChat } from 'react-native-gifted-chat';
import { StyleSheet, Text, View } from 'react-native';

export default function App() {
  const [messages, setMessages] = useState([
    {
    _id: 1,
    text: 'This is a quick reply. Do you love Gifted Chat? (radio) KEEP IT',
    createdAt: new Date(),
    user: {
      _id: 2,
      name: 'React Native',
    },
  },
  {
    _id: 2,
    text: 'This is a quick reply. Do you love Gifted Chat? (checkbox)',
    createdAt: new Date(),
    user: {
      _id: 3,
      name: 'React',
    },
  }
  ]);

  const onSend = (newMessage = []) => {
    setMessages(GiftedChat.append(messages, newMessage));
  };
  
  return (
    <GiftedChat
      messages={messages}
      onSend={newMessage => onSend(newMessage)}
      user={{
        _id: 1,
      }}
    />
  );
}

This example contains 2 messages, both with different user ids, but the messages are displayed on the left side. I also saved the messages in backend, and while writing new messages is not a problem, pulling them from backend and displaying them is.

I also modified renderMessage property of giftedChat, but to no avail. I am using a server that accepts group chats only, could that be the problem? Any ideas? Thanks


Solution

  • I am very glad to answer this question for the right alignment one message in right and one message on the left you have to use this

    1. use RenderBubble

      <GiftedChat renderBubble={this.renderBubble}. 
                  isLoadingEarlier={true}/>
      
    2. in renderBubble function, check this condition ( sender id or current message user id )

      currentMessage.user._id == this.state.senderData.id) {
            <Bubble
                 {...props}
                 wrapperStyle={{
                   right: {
                     height: 200,
                     backgroundColor: 'blue',
                   },
                 }}
               />
          } else {
      
      <Bubble
               {...props}
               wrapperStyle={{
                 left: {
                   backgroundColor: '#f0f0f0',
                 },
               }}
             />
      }
      

    that all in this code we differentiate the message in the left side or right side