Search code examples
reactjsmaterial-uitypography

Typography in React Material-UI


I've this textbox:

<Typography component="p" className={classes.text}>
        {this.props.post.text}
</Typography>

I'd like to be able to include paragraphs but all text entered into it gets printed on one line.

The documentation suggests that paragraph is defaulted to false so I must set it to `true.

I've tried the following:

<Typography component="p" className={classes.text} paragraph="true">

I also tried:

<Typography component="p" className={classes.text} paragraph={true}>

Neither work so all my text still gets printed to one line.

How do I get the paragraphs to show?

Additional info: As I now understand, the paragraph={true} attribute in Typography just adds a bottom-margin to the whole text. I.E. my one block of text is a paragraph. If I want another paragraph I would have to add another Typography. Something like:

<Typography component="p" className={classes.text} paragraph={true}>
        {this.props.post.text}
</Typography>
<Typography component="p" className={classes.text} paragraph={true}>
        {this.props.post.text2}
</Typography>

This is not exactly what I want. Perhaps what I should be aiming for is to have the return characters in my input text recognised. Is this correct and if so, how is it done?

I tried this:

  <pre>
    <Typography component="p" className={classes.text}>
      {this.props.post.text}
    </Typography>
  </pre>

The tag preservers the whitespace and line breaks inside the tags as is.

This is not suitable though. If I have long line the text does not wrap at the Card width. Instead anything beyond the width of the card becomes truncated. Clearly I want it all. I want my text to wrap in the card and also for it to support new lines and paragraphs. How is this done?


Solution

  • For new paragraphs

    <Typography>
      {this.props.text.split("\n").map((i, key) => {
        return <p key={key}>{i}</p>;
      })}
    </Typography>
    

    For just new lines

    <Typography>
      {this.props.text.split("\n").map((i, key) => {
        return <div key={key}>{i}</div>;
      })}
    </Typography>