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?
A better way is to use power of css:
white-space: pre-line
"New line" character will be respected if you use this css property.
Edit: Help from Ionut-Alexandru Baltariu
<Typography id="modal-description" sx={{ whiteSpace: 'pre-line'}}>
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>
I tried your answer and it worked perfectly as needed. However, the console returns a minor error
Warning: validateDOMNesting(...):
<p>
cannot appear as a descendant of<p>
.
I improved on your answer slightly by replacing the <p>
tags in your .map()
with <Typography>
and wrapping it all in a <div>
instead, like so:
<div className={classes.text}>
{this.props.post.text.split('\n').map((i, key) => {
return <Typography key={key} paragraph variant="body1">{i}</Typography>;
})}
</div>
(you can replace body1
with whichever variant you want!)
This seems to get rid of the warning for me and I hope works as you intended.