Using CSS to render line breaks in JSON data

·

1 min read

I recently worked on a React website which required me to list a bunch of projects with titles and descriptions.

The data was in this format:

{
  title: "Project 1",
  description: "My name is Project 1.\nI am the second line of project 1"
}

Now if I try to render this text inside a React component, it renders the \n as is without giving a line break that I expected.

At first, I thought of using JavaScript to tackle this and figuring where the \n is and then breaking the text into separate <p> tags from there but I remembered there was a word-break property in CSS, so I decided to search if there is a property for line breaks too.

And lo behold there is, you simply need to use the CSS white-space property on the paragraph element and it will render the text properly with a line break.

p {
  white-space: pre-wrap;
}

CSS Tricks has a nice article explaining all the other values you can add to it.

Just the thought of doing this in JavaScript felt like a hack. I'm sure there might be some edge cases that might need JS but for simple use cases, this is an easy and valid approach.