Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component.

When I input a long text, it overflows its container without breaking onto a new line:

import React from "react";
import { Redirect } from "react-router";
import { withRouter } from "react-router-dom";

import Container from "@material-ui/core/Container";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";

function Homepage() {
  return (
    <div>
      <React.Fragment>
        <CssBaseline />
        <Container fixed>
          <Typography variant="h1" component="h2" align="center">
            123 456 789 qwertyuiopasdfghjklzxcvbnm
          </Typography>
        </Container>
      </React.Fragment>
    </div>
  );
}

export default withRouter(Homepage);

Here is an image for reference:

https://i.stack.imgur.com/G3X9w.png

This issue occurs in both mobile and desktop views.

Is there a solution to ensure that long words are split onto a new line when they reach the maximum width of the container?

Answer №1

Solution

For handling long strings without spaces, you can utilize the word-wrap property, which is effective for Material-UI's Typography.

wordWrap: "break-word"

Reference: QA: wrap long string without any blank


Demo

<Typography
  variant="h1"
  component="h2"
  align="center"
  style={{ wordWrap: "break-word" }}
>
  123 456 789 qwertyuiopasdfghjklzxcvbnmdfsafasfasfadfaf
</Typography>

Give it a try online:
https://codesandbox.io/s/wizardly-noether-n9435?fontsize=14&hidenavigation=1&theme=dark

Answer №2

I stumbled upon this fantastic solution and decided to incorporate it globally into my typography settings. To implement this, simply include keikai's answer in your createMuiTheme.

//theme.jsx or theme.tsx
import { createMuiTheme, responsiveFontSizes } from '@material-ui/core/styles';


let theme = createMuiTheme({
  overrides: { 
    MuiTypography: { 
      root: { 
        wordWrap: "break-word"
      }
   } 
  }
});

export default theme;

Answer №3

Important Update: 24th November 2021 - Deprecated createMuiTheme Here's the updated version that will work smoothly:

const theme = createTheme({
    components: {
        MuiTypography: {
            styleOverrides: {
                root: {
                    wordWrap: "break-word"
                },
            },
        },
        MuiCard: {
            styleOverrides: {
                root: {
                    width: "auto",
                    margin: 10,

                },
            },
        },
    },
});

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

Storing information in a database using Phantomjs

My app is built on phantomjs and here's how it currently operates: 1. A php script retrieves data from my postgres database as an array, 2. The array of data is then passed as an argument to a shell_exec command running a phantomjs script, 3. Phantomj ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

Unlock the power of viewing numerous inputs simultaneously

Seeking guidance on how to allow users to preview images before uploading them. Currently, my code successfully previews images for one input field, but I am facing challenges when trying to add multiple pairs of inputs and images. How can I implement mul ...

Deletion of ::before and ::after pseudo-elements upon addition of the class is-sticky

One issue I'm facing is that when the class is-sticky is applied to my menu, the ::before and ::after pseudo-elements on my logo become unnecessary. As I am not very proficient in JQuery, I have been unable to resolve this by searching online. The HT ...

Is it possible for CSS to accurately crop images by pixels [Sprite Box]?

I attempted to replicate the math used for the previous image cuts and added my own image, but it appears blank. Can you identify where the issue lies? #paymentForm { -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webk ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

Utilizing a React component as a function: A step-by-step guide

I am looking to implement a material ui dialog that can handle the result from JavaScript for a simple yes/no prompt. This is how I envision it working: <MyPromptComponent /> { MyPromptComponent.show('Do you really want to?').then((res ...

Leveraging Angular to incorporate HTML templates from one component into another component

I am currently working with two components. The first one is a table component, identified by the selector 'table-component', which has standard filtering capabilities. The second component is designed for displaying the table on a page. This me ...

Testing React applications with Redux Toolkit using the React Testing Library

Currently, I am utilizing the Redux Toolkit approach by developing slices with reducer and extra reducers as well as thunks with createAsyncThunk API. As I delve into testing, I am eager to unveil the most effective way to test these components using React ...

Obtain an array as the response from an Ajax call

When passing data using Ajax request, I utilize the code below: var query = { "username" : $('#username').val(), "email" : $('#email').val(), } $.ajax({ type : "POST", url : "system/process_registration.php", ...

Can you confirm the mobile type, please? Using JavaScript to display a div only once based on the mobile type

Is there a correct way to determine the type of mobile device I'm using? Are there alternative methods to check for the mobile type? Take a look at my approach in the code below. How can I test this using a tool? Does anyone have insights on checki ...

Identifying browsers with Zend Framework versus JavaScript

Currently, I am working on developing an application that demands the capability to upload large files. After much consideration, I have opted to utilize the FormData object as it allows me to provide progress updates to the user. Sadly, Internet Explorer ...

Ways to smoothly conclude a loading animation in real-time

I have a unique challenge of creating a loading animation using Adobe After Effects instead of CSS. The main goal is to develop an animation that continuously loops, but when the loading process stops, it ends with a distinct finishing touch. For instance, ...

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Javascript/Typescript Performance Evaluation

I am looking to create a visual report in the form of a table that displays the count of each rating based on the date. The ratings are based on a scale of 1 to 5. Below is the object containing the data: [ { "Date": "01/11/2022", ...

The variable 'firebase' is nowhere to be found

I am encountering an issue with the error message 'Can't find variable: firebase' and I am struggling to identify the cause of this error. I have installed firebase using 'yarn add firebase' and double-checked that it is properly i ...

How can you loop through keys and values in a JSON object using JavaScript?

I am attempting to cycle through the JSON data below: { "VERSION" : "2006-10-27.a", "JOBNAME" : "EXEC_", "JOBHOST" : "Test", "LSFQUEUE" : "45", "LSFLIMIT" : "2006-10-27", "NEWUSER" : "3", "NEWGROUP" : "2", "NEWMODUS" : "640" } The keys in this JSON are d ...

Trouble with action creators not appearing in "this.props" while using redux-form version 6.0.0-rc.3

After updating redux-form from version 5.3.1 to 6.0.0-rc.3 for Material-UI integration, some changes were made: Fields removed from render(): const { handleSubmit, fields: { email, password, passwordConfirm }} = this.props; Errors validation removed f ...