1

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?

3
  • 2
    If the string is just text and line breaks, why not split up the string based on newline characters and then build a new element with <br/> tags instead, and avoid using the rather nasty dangerouslySetInnerHTML altogether? Commented Dec 18, 2020 at 14:13
  • 1
    Check this question stackoverflow.com/questions/31001066/… Commented Dec 18, 2020 at 14:16
  • @AbdelrhmanArnos Yes, it has a relevant answer. Thank you Commented Dec 18, 2020 at 14:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. All three methods worked for me. Can you please elaborate a little, why everyone advice to use dangerouslySetInnerHTML as the last option? What is the drawback?
Using dangerouslySetInnerHTML can open you up to a cross-site scripting (XSS) attack.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.