dracarys
dracarys

Reputation: 1121

React Material UI Grid align items conditionally to either left or right of screen

I am creating a chatbot and using React and Material UI. I am running into a problem with the Grid component. I am trying to align the bot messages to the left side of the screen and the user messages on the right side of the screen, however it is not working.

I have tried using alignItems prop on the Grid component, I have also tried using the CSS property float='right' and float='left'. But both do not seem to work.

I have a code sandbox link below showing a minimum reproducible example. Any help will be appreciated.

https://codesandbox.io/s/react-chat-cuvfm?file=/src/App.js

Current Output: enter image description here

Intended Output: All the blue bubbles should be at the right end of the screen

Upvotes: 0

Views: 1111

Answers (2)

Mayank Chaudhary
Mayank Chaudhary

Reputation: 3

Instead of using the float property, you can just set marginLeft: 'auto' in ChatBubble/styles.js

This will set the left margin as max as possible for the user chat bubble also, adding marginRight to the recipient chat bubble is not necessary. So, you can avoid handling orientation for the recipient.

  userChatBubbleOrientation: {
    // float: "right",
    marginLeft:'auto'
  },
  recipientChatBubbleOrientation: {
    // float: "left"
    // marginRight:'auto'
  },

Upvotes: 0

Mihai T
Mihai T

Reputation: 17697

As far as i could see if the message has ID = 0 then it's user message. Then, in your ChatBubble component , in JSX add

In ChatBubble styles.js

  userChatBubbleOrientation: {
    justifyContent: "flex-end"
  },
  recipientChatBubbleOrientation: {
    justifyContent: "flex-start"
  } 

In ChatBubble Component

  const chatBubbleOrientationStyles =
    props.message.id === 0
      ? {
          ...styles.userChatBubbleOrientation
        }
      : {
          ...styles.recipientChatBubbleOrientation
        };
<Grid
  container
  style={chatBubbleOrientationStyles}
>

Use flexbox instead of float. Never use float for layout purposes. Also, Material UI uses flexbox so make use of that by adding justifyContent:flex-end to your bot(user) messages to align them their content ( img + text ) to the right

Upvotes: 1

Related Questions