React - Material UI Typography how to break long string to multiple lines
Asked Answered
I

4

8

I'm using ReactJS and the components library called MaterialUI. I'm having an issue with the Typography component.

What happens is that if I write a long text it exceed its container and doesn't go on 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);

below an image:

enter image description here

This happens in the mobile mode and also in desktop mode.

Do you know how to fix this behavior? I would like the long words will be split on a new line if the maximum width of the container has been reached.

Irritant answered 11/3, 2020 at 7:56 Comment(0)
W
20

Solution

Use word-wrap, it works for Material-UI's Typography.

wordWrap: "break-word"

Ref: QA: wrap long string without any blank


Demo

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

Try it online:
Edit wizardly-noether-n9435

Wellfounded answered 11/3, 2020 at 8:22 Comment(0)
C
1

I came across this and it's a great fix. I ended up adding this in globally to my typography. If you need this then simply add keikai's answer to 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;
Clairvoyant answered 11/3, 2021 at 18:48 Comment(0)
O
0

Update 24-11-2021 createMuiTheme deprecated new version that work:

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

                },
            },
        },
    },
});
Overtire answered 24/11, 2021 at 11:55 Comment(0)
D
0

Use max-width instead of width and text will automaitcally wrap inside typography.

sx={{maxWidth:400px}}

Without using any word wrap worked for me.

Drypoint answered 1/8, 2024 at 7:20 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.