Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve space in React rendered element

Tags:

reactjs

From my backend service a string containing spaces is returned. When I console.log this value in my render method it shows the raw string with spaces.

The rendered element, however, is missing the values.

Example:

const a = "I am a text string"

is different from:

const a = "I  am a text string"

(Notice the extra space between "I" and "am".

The render method seems to be removing the extra space from my rendered output.

This is just an example, but the raw data that I try to show the end user has to contain the extra space. How can I force React to render the raw string, instead of doing some kind of text-formatting on it?

like image 402
Thomas Darvik Avatar asked Mar 29 '26 22:03

Thomas Darvik


1 Answers

I am not sure if React JS messes up the space as it's just HTML. Use the following CSS on the element:

white-space: pre-wrap;

Working Demo: wmnk7rmq8 - CodeSandbox

like image 107
Praveen Kumar Purushothaman Avatar answered Apr 01 '26 11:04

Praveen Kumar Purushothaman