简体   繁体   中英

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: 在此处输入图片说明

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

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

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'
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM