Positioning React Material UI Grid items dynamically on either side of the screen based on conditions

I am currently working on a chatbot project using React and Material UI. I have encountered an issue with the Grid component in my application. My goal is to align the bot messages to the left side of the screen, while positioning the user messages on the right side. Unfortunately, my attempts to achieve this alignment have been unsuccessful.

I have experimented with the alignItems prop on the Grid component and have also tried using the CSS properties float='right' and float='left'. Despite these efforts, I have not been able to achieve the desired layout.

If you would like to take a look at a minimal reproducible example, I have provided a link to a code sandbox below. Any assistance or guidance on resolving this issue would be greatly appreciated.

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

Current Output: https://i.sstatic.net/LBbwU.png

Intended Output: Ideally, all the blue bubbles should be positioned at the right end of the screen

Answer №1

From what I have observed, if the message has an ID of 0, then it is a user message. So, in your ChatBubble component, you can add the following in JSX:

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

It's recommended to use flexbox instead of float for layout purposes. Material UI also utilizes flexbox, so adding justifyContent:flex-end to your bot(user) messages will align their content (image + text) to the right.

Answer №2

Forget about using the float property, just go ahead and specify marginLeft: 'auto' in ChatBubble/styles.js

By doing this, you'll maximize the left margin for the user chat bubble without needing to add marginRight to the recipient chat bubble. This way, you can simplify handling orientation for the recipient.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for using CSS to position a sidebar on the right side of the screen:

I've been working on creating a simple sidebar and have reached this point in my code. However, I'm struggling to get it to float to the right. It's all a bit confusing for me. If you'd like to take a look at the code, here is a link t ...

"Customizing the appearance of Angular Formly forms by adding classes to the surrounding div element

<formly-form model="vm.model" fields="step.inputs" options="vm.options"> <div style="text-align:right"> <button type="submit" wz-next class="btn btn-primary submit-button" ng-disabled="innerForm.$invalid">Next</button> ...

What is the best way to incorporate a callback into a function at the exact moment it is activated?

Looking to incorporate a callback into the function Notification.requestPermission(). The challenge lies in not knowing exactly when this function will be triggered. My current approach involves binding the browser notification permission box to achieve a ...

Using angularjs ng-repeat in combination with owl-carousel

<div class="owl-carousel"> <div ng-repeat="items in itemlist"> <a href="series.html"><img ng-src="{{items.imageUrl}}" /></a> </div> <div> <a href="series.html><img src="http://p ...

Struggling with positioning of dropdowns on Bootstrap 4-alpha-2 navbar

The screenshot above showcases the responsive design functionality in Safari on OS X. The code snippet below demonstrates how the navbar is created, revealing that the dropdown menu on the right extends beyond the page. How can this issue be rectified? ...

If the user confirms it with a bootstrap dialog box, they will be redirected to the corresponding links

Firstly, I am not interested in using javascript confirm for this purpose. Please read on. For example, adding an onClick attribute to each link with a function that triggers a system dialog box is not what I want. Instead of the standard system dialog bo ...

Is it possible for function in module.exports to access global variable within a module?

Suppose I have some code in a module: var foo = "bar"; module.exports = function() { console.log(foo); } And I try to access it from another module like this: var mod = require('above-module'); mod(); Will the second module be able to ac ...

What is the best way to center a div within another div without using the margin tag?

I am struggling to find a way to center a container (div) on my webpage. I've tried various methods like using margin:auto, margin:0 auto;, margin-left:auto;, and margin-right:auto;, but none of them seem to work. Additionally, I'm unsure about ...

The appropriate method for showcasing cards within lists, such as in the platform Trello

I'm in the process of developing a project similar to Trello, but I'm facing some challenges on how to proceed. Initially, I created an 'init' function within my AngularJS Controller to handle HTTP requests: $scope.loadLists(); ...

Two functions are contained within an object: Function A and Function B. Function A calls Function B from within its own code

If I have two functions within an Object. Object = { Function1() { console.log('Function 1') }, Function2() { this.Function1() } } The Function1 is not being executed. Can someone explain why this is happening an ...

How to set a maximum width in IE8 when using width:100%?

After researching online, I am still unable to get it to work. I have a basic HTML layout that I have been testing across different browsers. Knowing the quirks of IE, I wasn't surprised when the max-width CSS code didn't function as expected. Ho ...

How to Implement Snap-Enabled Dragging in a Container Using jQuery UI

Issue Description (Fiddle): I am using the jQuery UI's .draggable() function to make the red element snap inside the blue container. However, it is snapping to one edge only instead of completely fitting inside (both edges). It requires further dragg ...

Utilizing a wysiwyg text editor in conjunction with Angular 2

I am currently implementing a wysiwyg feature in my Angular2 project. When I include the code in the index.html page (the root page), it functions correctly. However, when I try to use it in a child view HTML file, the CSS and JavaScript do not load prope ...

Executing Basic Calculations Instantly with Live Data in Qualtrics

I am encountering an issue with displaying the values on a slider in Qualtrics. I need to show the value where the respondent has placed the handle, as well as the complementary value from the other end of the scale. For example, if the user has chosen 55, ...

Experimenting with directive using jasmine

I've been working on this directive but I'm having trouble writing the jasmine test for it. Any suggestions? import { Directive, Output, EventEmitter, HostListener } from '@angular/core'; @Directive({ selector: '[ctrlKeys]&apos ...

Creating a 5px wide bold horizontal line in CSS3

I experimented with the below CSS3 code to create a 5px wide horizontal line: <hr style=" border: solid 1px red;padding-top:10px; margin:25px auto 15px auto;clear:both" /> Unfortunately, instead of a line, I ended up with a 5px wide red rectangle. ...

Utilizing i18n's useTranslation and Redux's connect Higher Order Components to export components efficiently

My application has been utilizing Redux for quite some time, with the component exports structured like this: export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); Now, I am integrating an i18n translation library and would like to use ...

What methods can I use to ensure the accuracy of my form and securely store my information in a database using Angular,

I am currently working on an Angular project where I aim to create a form, validate it, and store data in my database using PHP and MySQL. However, I have encountered some challenges while attempting to accomplish this task. Here are the errors that I have ...

Determine the number of visible li elements using jQuery

Currently, I am utilizing a jQuery script to count the number of li elements in my HTML code. Here is an example of the setup: HTML: <ul class="relatedelements"> <li style="display:none;" class="1">anything</li> <li style="disp ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...