Creating dynamic text bubble to accommodate wrapped text in React using Material-UI (MUI)

I am currently developing a chat application using ReactJS/MUI, and I have encountered an issue with the sizing of the text bubbles. The bubble itself is implemented as a Typography component:

<Typography variant="body1" sx={bubbleStyle}>
    {text}
</Typography>

The styles for the bubble are defined as follows:

const bubbleStyle = {
    bgcolor: fromUser ? theme.palette.primary.main : '#f1f1f1',
    color: fromUser ? 'white' : 'black',
    p: 1,
    borderRadius: '8px',
    maxWidth: '65%',
    wordBreak: 'break-word',
    display: 'inline-block',
    my: 0,
    fontFamily: 'Inter, sans-serif',
    fontWeight: '100',
    fontSize: '14px',
};

Currently, when the text inside the bubble exceeds a single line, the width of the bubble extends to 65%, resulting in unnecessary white space on its right side. An example of this issue can be seen in the following image:

problem bubble

I have already tried several solutions to address this problem, including setting width='fit-content', using hidden <div> or <span> elements, employing a ResizeObserver, creating a nested MessageComponentText component, and dynamically measuring the text with JavaScript for resizing purposes - none of which have provided a satisfactory solution.

Although I have explored similar HTML/CSS-based approaches to resolve this issue, my limited knowledge of these technologies has hindered my ability to adapt those solutions to MUI.

Answer №1

From my understanding, the optimal solution seems to be using the CSS property word-break: break-all. This will help in breaking up long words to fit the content area and eliminate any unnecessary spaces. I've yet to come across a method that retains the word structure while eliminating additional spaces.

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 expanding a carousel Material-UI card when hovering

I'm working on a Carousel feature inspired by Netflix's design, where hovering over a card will enlarge it and display more details. The issue I am facing is that instead of only enlarging the hovered card, all other cards are also getting enlar ...

Guide on establishing two loops in React JS

I'm receiving a JSON array that contains nested arrays. I attempted to iterate through it using two loops, but so far, I haven't been successful. {this.state.listOfAlarms && this.state.listOfAlarms.map((alarms) => {alarms.repo ...

Using jQuery, set a restriction on the total number of options in three dropdown menus to

I am currently facing a challenge with 3 dropdowns, each containing 8 options. My aim is to restrict the total selection across all three dropdowns to 8. For instance, if I choose 7 in the first dropdown, I should only be able to pick 1 in the next two. Si ...

Creating a Text Typer ReactJS component that functions properly regardless of whether or not it is used within StrictMode is no

My goal is to develop a custom Text Typer component that displays text character by character every 100ms. While it works perfectly fine in production, I encounter issues when testing it in the development environment. Despite trying various solutions, tw ...

Tips for validating email addresses and enforcing minimum length requirements

In order to validate email input for the correct format and ensure minimum length validations for first name and password, I am looking to utilize only bootstrap. While I have successfully implemented required field validations for the inputs, I am unsure ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

Why am I receiving a warning about adding a subroute when I already have a component?

<Route path="/users/:userId" component={UserShow}> <Route path="/location/:locationId" component={LocationShow} /> </Route> A message popped up in the console of my Chrome browser: bundle.js:887 Warning: Avoid using both <Rout ...

Define the number of columns in CSS Grid and ensure that rows wrap accordingly

tag, I need to utilize CSS grid with 12 columns while ensuring that the tables stack in a column layout when the viewport size decreases. Is it possible to accomplish this using CSS grid? My research suggests that for row wrapping, I must use either ' ...

How can I modify the appearance and behavior of an HTML button?

I simply need to update the button class and value in order to change the button's functionality. After successfully changing the value and class, the functionality remains the same as the old class. Why is this happening? Could it be that the brows ...

Utilize CSS to incorporate special characters as list markers

Is there a way to use CSS to make the list marker in an HTML list display as "►"? ...

Creating a custom styled-component in Typescript for rendering {props.children}

One of my components is called ExternalLink which is used to display anchor tags for external URLs. This component has been styled using styled-components. Check out the CodeSandbox demo here ExternalLink.tsx This component takes an href prop and render ...

Creating a dynamic return statement in typescript: A step-by-step guide

I am looking to dynamically set a return value to a variable based on values retrieved from an API. The current function in question uses static values: this.markDisabled = (date: NgbDate) => { return (this.calendar.getWeekday(date) !== 5 && ...

Sending information to a server using JavaScript

Greetings everyone, this is my first time posting here and I would appreciate detailed guidance in your comments. Just a little background about myself: I am a second-year college student with one year of Python training. I only recently started learning ...

Tips for restoring lost data from localStorage after leaving the browser where only one data remains

After deleting all bookmark data from localStorage and closing my website tab or Chrome, I am puzzled as to why there is still one remaining data entry when I revisit the site, which happens to be the most recently deleted data. This is the code snippet I ...

Preventing me from instantiating objects

I've been struggling with an issue for a while now consider the following: export abstract class abstractClass { abstract thing(): string } export class c1 extends abstractClass { thing(): string { return "hello" } } export cla ...

Error thrown by webpack: Module 'pug' not found when attempting to access get-api

After setting up webpack in express, a new folder was created. When I try to run bundle.js, it shows the message "server is running on port 3000". However, when I access the API at http://localhost:3000/api/test, the whole bundle.js loads in the console an ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

Adjust SVG Checkbox to eliminate any unnecessary padding

I am attempting to customize the MUI5 checkbox CSS fields, and here is the current status: https://i.stack.imgur.com/BROpS.png These are my CSS classes: MuiCheckbox: { styleOverrides: { root: { ".MuiSvgIcon-root": { backgro ...

What causes my CSS to be disrupted by a line break in one instance but not in another? (view demonstrations)

https://i.stack.imgur.com/bitod.png In comparing this particular fiddle with another version of the same fiddle, the only variance is that in the second one, there is </label><label for="address_zip" class="zip"> without a line break following ...