showing <li> elements on both the left and right sides based on the specified condition

I am struggling to show messages one by one using the 'li' tag, with the intention of having our messages appear on the right side and others on the left side in a react Chat app. However, the issue arises when I attempt to use float left or float right, causing all elements to collapse onto the same line like this

https://i.sstatic.net/nDN3S.png

The styling code for my react chat is as follows:

      {this.state.chats.map(chat => (<div key={chat.timestamp}>
        {this.state.user.uid === chat.uid  ?(
       <li className=" self" style={{listStyleType:"none",overflow:'hidden',marginLeft: 2 +'px',float:'right',display:'inline-block',
            backgroundColor:"whitesmoke",margin:2 + "em",padding:13+'px',width:'max-content',borderBottomLeftRadius:11+'px',
            borderBottomRightRadius:11+'px',borderTopLeftRadius:11+'px'}}>

                <div className="message text-dark">{chat.content} </div>
        </li>
            
          ):(
                <li className="other" style={{listStyleType:"none",overflow:'hidden',marginLeft: 2 +'px',float:'left',display:'inline-block',
            backgroundColor:"blanchedalmond",margin:2 + "em",padding:13+'px',width:'max-content',borderBottomLeftRadius:11+'px',
            borderBottomRightRadius:11+'px',borderTopRightRadius:11+'px'}}>
          
                 <div className="message text-dark">{chat.content}</div>
            
            </li>
            
          )}
        </div>
        ))}

Update: consider floating each individual div

https://i.sstatic.net/asEwD.png

Answer №1

.self {
  background: orange;
  float: right;
  clear: both;
}

.other {
  background: blue;
  float: left;
  clear: both;
}
<ul>
  <li class="self">message</li>
  <li class="self">message</li>
  <li class="self">message</li>
  <li class="self">message</li>
  <li class="other">message</li>
  <li class="other">message</li>
  <li class="other">message</li>
  <li class="self">message</li>
</ul>

https://developer.mozilla.org/en-US/docs/Web/CSS/clear Explore the clear attribute to handle floated elements effectively.

Answer №2

Unique Flexbox Solution:

.left {
  display: flex;
  justify-content: flex-start;
}

.right {
  display: flex;
  justify-content: flex-end;
}
<ul>
  <li class="left">
    Displaying others message
  </li>
  <li class="right">
    Displaying your message
  </li>
</ul>

Unique Solution 2

Consider adjusting <li> to occupy the entire line, and apply float: left/right to the internal <div>

Here is an example: https://jsfiddle.net/L1g6wx34/

.left {
  float: left;
}

.right {
  float: right;
}
<ul>
  <li>
    <div class="left">
      Displaying others message
    </div>
  </li>
  <li>
    <div class="right">
      Displaying your message
    </div>
  </li>
  <li>
    <div class="right">
      Displaying your message
    </div>
  </li>
</ul>

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

Bring in data from a local JSON file into the state of a React

I am currently developing an application to help me practice utilizing routes, so I am starting with static, local test data in json format. This data is an object comprised of two arrays: folders and notes. My goal is for the initial state of my app to ...

Having trouble incorporating Bootstrap 5's SASS variables into my project's SASS files

I'm attempting to utilize Bootstrap 5 variables in my custom styles.scss file. I have integrated the entire Bootstrap 5 source code into my project. I have noticed that I need to import specific .scss files in my styles.scss file for it to function co ...

React: Having trouble displaying routes in a separate component

Presenting the Navbar component: const Navbar = () => ( <nav className="navbarLogged"> <ul> <li><NavLink to="/">Trending</NavLink></li> <li><NavLink to=" ...

What is the best way to modify this CSS code for use in a React Native

Encountering an issue while trying to apply this CSS property in a React Native project. border-radius: 50% / 100%; Attempting the following: borderRadius: '50% / 100%' An error message is displayed stating "Java.lang.string cannot be cast to ...

The inner HTML functionality in Angular 2 seems to be malfunctioning when dealing with HTML tags

I am facing an issue with an array that includes displayName with HTML tags: this.topicsList = [ {id: "173", name: "Discussion1", displayName: "Discussion1", status: 1}, {id: "174", name: "discussion123", displayName: "discussion123", status: 1}, {id: "19 ...

AngularJS Cascading Dropdowns for Enhanced User Experience

There is a merchant with multiple branches. When I select a merchant, I want another dropdown list to display the data from merchant.branches. The following code does not seem to be fixing the issue: <label>Merchant:</label> <select ng-if= ...

Sending a null value to the state is necessary to ensure that the ImageField in React and Django is updated to null

What I want to achieve I am trying to set null in the ImageField. My goal is to make the value of the ImageField for a model null. Issue Upon sending a Patch request, I encountered the following error. The submitted data was not a file. Check the encodin ...

Find your way to a unique div created through a while loop

Describing my issue clearly, I am using PHP to retrieve data from MySQL. The table contains multiple records. To display table records, I have implemented a while loop with mysqli_fetch_array() as the condition. These records need to be echoed out (in HT ...

Is it possible to coerce multiple Context Consumers into sharing their state?

Currently, I am utilizing the React Context API to avoid prop drilling in my application. My Context consists of a useState and various state-updating functions encapsulated within an object that is passed as the value prop of ActionsContext.Provider. The ...

What advantages can be gained from having multiple package.json files within a single application?

Embarking on the journey of creating my inaugural full react web application entirely from scratch. Previously, I've mainly worked on assignments that were partially pre-made for me. While setting up my project, I couldn't help but notice that I ...

Integrate a third-party REST API with ReactJS and NodeJS

Currently in the process of learning ReactJS and NodeJS. My developer team has set up a create-react-app boilerplate for our project. We need to interact with an External REST API service to make calls, retrieve data, and update data. Question: ReactJS i ...

Tips for personalizing Material-UI and styled-components styles using prop-based customization

Utilizing Material-UI and styled-components, I encountered a scenario where I needed to override the styles of a Material-UI component with styled-components based on a passed prop. Initially, my attempt involved passing an additional prop to the styled-c ...

Learn the steps to Toggle Javascript on window resize

Is there a way to toggle Javascript on and off when the window is resized? Currently, resizing the window causes the navigation bar to stick and remain visible above the content. <script> if ( $(window).width() <= 1200 ) { }else{ $('nav& ...

Ways to expand media queries using sass

I have been using media queries to modify my code. @media (min-width: 576px) .modal-dialog { max-width: 500px; margin: 14% auto; } I want to change the media query, but after searching online, I couldn't find a suitable solution. I know the foll ...

Using Formik with MUI Multiple Select

Exploring the world of MUI and Formik, I encountered a challenge with creating a multiple Select in my form. It's my first time working with these tools, so I have a question regarding the implementation. Here's what I've tried based on the ...

Encountered an error while trying to filter markers and list using Knockout and Google Maps - Uncaught TypeError: Unable to locate property 'marker' of undefined

I am looking to enhance user experience by implementing a feature where clicking on a marker or a city name will display the info.window specific to that marker. HTML: <!DOCTYPE html> <html> <head> <title>Exploring Mag ...

To modify the text within the pagination select box in ANTD, follow these steps:

Is it possible to modify the text within the ant design pagination select component? I have not been able to find a solution in the documentation. I specifically want to replace the word "page" with another term: https://i.sstatic.net/w55hf.png ...

Guide to personalizing React Material-UI Next components

I'm currently utilizing Material UI's next branch for my project and I want to customize the style of the TableHead component within the table. My approach was to create a new component called MyTableHead, wrap it around the TableHead component, ...

Unable to execute the npm run dev command

How can I start this React app? I tried using npm run dev An error occurred: npm run dev > [email protected] dev > cross-env NODE_ENV=development npm-run-all -p api client:dev server:dev styles:w ... Error: Node Sass does not yet support y ...

The images are positioned within the middle of the page, directly beneath the sidebar, rather than at the top. (Vue.Js)

I'm currently working on a Vue.JS photo website and I've hit a roadblock as described in the title. Despite trying various solutions, after spending two hours back and forth with ChatGPT, I've decided to seek help here. Below is the code sn ...