Preserve new lines and spacing in CSS

Problem

You got some text (maybe from a server) that has newlines and spacing. This what the text looks like in JavaScript:

const text =
  "I have a newline here\n and some extra white           space for some reason.";

Now you want to display it in HTML, so you render it in JSX:

<p>{text}</p>

And this is the result:

I have a newline here and some extra white space for some reason.

The newlines and spaces are ignored.

Solution

If you want to preserve new lines and white space, you can use the white-space CSS property with the pre-wrap value:

p {
  white-space: pre-wrap;
}

So the JSX now becomes:

<p style={{ whiteSpace: "pre-wrap" }}>{text}</p>

And this is what it looks like:

I have a newline here and some extra white space for some reason.

You can also use a preformatted text element <pre>.

Other things to read

Popular

Previous/Next