Preserving line breaks from an API string response when rendered in your React component
If you’ve ever worked with an API that returns a string containing line break characters and wrongly assumed they would be preserved by default when you render the text in your React component, then you’re not alone. I assumed the characters would be preserved by default the first time I worked with such API response too but it wasn’t.
The API response could look something like this:
{ bio: "This is the first paragraph.\n\nSome text that make up the second paragraph.\n\nAnd finally, the third paragraph." }
The string returned from the API contains some newline characters (\n
) that we would like to preserve when we render the text. To preserve the newline characters we can use either the pre-line
or pre-wrap
value of the white-space
CSS property. This CSS property sets how white space is handled inside an element, that is, whether white space is collapsed or not, how it is collapsed, whether lines wrap or not and how they wrap.
.bio {
white-space: pre-line; /* or pre-wrap */
}
Add either of these two CSS styles to the component/element that is to display the string. While both pre-line
and pre-wrap
preserve line breaks, pre-wrap
preserves white space and pre-line
collapses them.
That’s it! Your rendered text should be displaying as desired now preserving the line breaks.
You can do some further reading on the white-space
CSS property on MDN:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space