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

Problems with implementing media queries in CSS

Our team is currently delving into the realm of responsive design and experimenting with a mobile-first framework. In an attempt to utilize media queries to adjust our layout based on screen size, we have crafted the following CSS: .flex, .cards, .card { ...

Receiving a warning: Invalid hook call alongside a Type error stating that properties of null cannot be read (specifically 'useContext') when utilizing a Material UI component

This section includes the following code snippet: import React, { useEffect } from "react"; import { useStore } from "../zustand/store"; import shallow from "zustand/shallow"; import Grid from "@mui/material/Grid"; ...

Access the information from the text box and text area, then store it into a cookie using either jQuery or JavaScript

I need to save the text entered in a textbox within an iframe. How can I achieve this using jQuery or JavaScript? Any assistance would be greatly appreciated. ...

What is the process of integrating Formik with Chakra using typescript?

I'm attempting to implement the following Chakra example in Typescript. <Formik initialValues={{ name: "Sasuke" }} onSubmit={(values, actions) => { setTimeout(() => { alert(JSON.stringify(values, null, 2)); actio ...

Unlocking the power of popups with Angular

As a beginner in AngularJS, I have encountered an issue where a popup appears when clicking on the "login/signup" button. Now, I want the same popup to appear when clicking on the "upload resume" button as well. Below is the code that is currently working ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

Incorporate Material Design Icons into your NPM Electron React application for sleek visuals

I am currently exploring how to incorporate Material Design Icons into an NPM Electron project with Webpack 4. The Google Github page suggests that the icons can be easily installed using npm install material-design-icons. However, based on this discussion ...

Struggling with repeatedly traversing characters in a string to solve the Palindrome challenge

I am working on a recursive solution for a Palindrome problem, but it seems that my code is only considering the first recursive call instead of the second one which should analyze all characters in the string. I suspect there might be a logical error in ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Tips for inheriting and overriding controller methods in AngularJS with Java as the base language:

I have a simple controller and I want to create a new controller that is very similar to it, but without copying too much code. angular.module('test').controller('parentController', parentController); parentController.$inject = [' ...

Export was not discovered, yet the names are still effective

There seems to be a slight issue that I can't quite figure out at the moment... In my Vue project, I have a file that exports keycodes in two different formats: one for constants (allCodes) and another for Vue (keyCodes): export default { allCodes ...

The utilization of local storage within Backgridjs

I am creating an app using Backbone.js (Marionette Framework) along with additional functionalities like Backgrid, Backbone local storage, Backbone Radio, epoxy, and Backbone relational model. Encountered Problem: An issue arises when utilizing the local ...

Struggling to figure out how to make this Vue function work

I am working with a list of tasks, where each task is contained within a div element. I am looking to create a function that changes the border color of a task to red when clicked, and reverts the previous task's border to normal. I have two files: &a ...

Enhance Your Joomla 2.5 Website with Custom CSS Specifically for iPad Viewing

Is there a way to load a specific CSS file when accessing my Joomla website through an iPad? I am running Joomla version 2.5. Although I have set up style-sheets for browsers like Internet Explorer and Firefox, I am unsure how to target the website to lo ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Capture sound and display waveform using React Native

Currently, I'm working on generating a waveform shape in React Native while recording audio. I've searched through various packages, but most of them require an audio URL and do not support real-time recording. In attempting to create my own solu ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

Avoid HTML code injection in an ExtJS4 grid by properly escaping the href attribute

I am facing an issue with escaping HTML in my Extjs grid. I have used the following configuration : return Ext.String.htmlEncode(value); In the renderer of my column, this method works perfectly for simple HTML tags like h1, b, i, etc. However, if I in ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...

tips for concealing the sorting icon in the DataTables header upon initial load

Is there a way to initially hide the datatable sorting icon upon loading, but have it display automatically when clicking on the header? I've been searching for a solution without success. https://i.sstatic.net/o2Yqa.png ...