David Johns
David Johns

Reputation: 1714

How to render multi line text with return characters in React component?

In my react app, I receive a text from the API like "Fully furnished luxury apartment for sale in San Fransisco.↵↵The following features are available↵↵-Water↵ -T...".

I need to render this text as a multiline text with blank lines instead of these return characters. I used the following method to render the text.

<div className="previewSectionDesc">
  {<div dangerouslySetInnerHTML={{ __html: propertyDescription }} />}
</div>

But this is what I received with no blank lines.

Fully furnished luxury apartment for sale in San Fransisco. The following features are available -Water -T...

How can I solve this?

Upvotes: 1

Views: 1034

Answers (2)

Orinayo Oyelade
Orinayo Oyelade

Reputation: 347

You can use the css white-space property to preserve the whitespace received. white-space: pre;

Upvotes: 1

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4754

HTML will ignore the line breaks in your text when displaying it. If you want to use dangerouslySetInnerHTML, you'll have to convert them to <br/> elements first:

<div className="previewSectionDesc">
  <div dangerouslySetInnerHTML={{ __html: propertyDescription.replace(/\n/g,'<br/>') }} />
</div>

You could also dispense with dangerouslySetInnerHTML by splitting your text on linebreaks, then showing each line as a <div>:

<div className="previewSectionDesc">
  {propertyDescription.split('\n').map((line, idx) => <div key={idx}>line</div>)}
</div>

Still another way would using the <pre> element rather than a <div>, where HTML will preserve your linebreaks.

Upvotes: 1

Related Questions