user7858768
user7858768

Reputation: 1026

React/MaterialUI: How to have whitespace from string be respected?

Attempting to use Typography from Material UI (https://material-ui.com/api/typography/)

The goal is to have new lines and spaces from the saved string to be respected.

Such that an example which has leading spaces and new lines would be rendered as:

const svg = d3.select("#chart-area")
   .append("svg")  
   .attr("width", 400)
   .attr("height", 400)

If I just use <Typography>{val}</Typography> then value gets rendered in one line such as:

const svg = d3.select("#chart-area") .append("svg") .attr("width", 400) .attr("height", 400)

Adding {{ whiteSpace: 'pre-line' }} makes Typography at least respect the new lines:

<Typography style={{ whiteSpace: 'pre-line' }}>{val}</Typography>

Rendering the string as

const svg = d3.select("#chart-area")
.append("svg")
.attr("width", 400)
.attr("height", 400)

But how do we have the component respect the new line and leading spaces?

Upvotes: 3

Views: 4865

Answers (2)

user9673071
user9673071

Reputation:

I know it's super late and not useful in particular to you anymore, but in case anyone needs a solution for this problem: style={{ whiteSpace: "pre-wrap" }}

From w3schools: "Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks"

With "pre-line" whitespaces collapse into a single whitespace

Upvotes: 3

Duderino9000
Duderino9000

Reputation: 2597

You could use a preformatted text element instead of <Typography />

<pre>
  const svg = d3.select("#chart-area")
.append("svg")
.attr("width", 400)
.attr("height", 400)
</pre>

Upvotes: 1

Related Questions