1

I've a string that contains html break tag to split the string as I would like to split the string into multiple lines but it doesn't seem to render the string as multi-line in UI. How can I achieve the following?

testString = "This is line one<br>This is line two<br>This is line three"

Expected Output:

This is line one
This is line two
This is line three

I read about dangerouslysettinginnerHTML but don't want to use it in my code. As far as split is concerned what I did was I tried

text.split('<br>').map(each => each + <br>)

but that didn't work. Any hint or help would be appreciated.

6
  • "but it doesn't seem to render the string as multi-line in UI." - what UI? A browser will render separate lines as a single line unless they contain <br> or <p>. Commented May 19, 2022 at 23:04
  • 2
    I understand your problem but but what exactly did you do that didn't work? Commented May 19, 2022 at 23:04
  • 1
    Generally speaking, the easiest way to do this with React is probably use dangerouslysetinnerHTML, but that's not a best practice. It's better to use javascript to split the string and then map the results while appending a br tag after each output Commented May 19, 2022 at 23:08
  • 1
    Yes I read about dangerouslysettinginnerHTML but don't want to use it in my code. As far as split is concerned what I did was I tried text.split('<br>').map(each => each + <br>) Commented May 19, 2022 at 23:13
  • 2
    A hint for future posts... code belongs in your question, not the comments. Commented May 19, 2022 at 23:30

1 Answer 1

1

The easiest way to do this outside of dangerouslySetInnerHTML is split and flat-map the string to an array of JSX elements.

{testString
  .split(/<br ?\/?>/)
  .flatMap((line, i) => [line, <br key={`line-${i}`} />])}

The regex delimiter is designed to split on any form of <br>, <br/> or <br />.

Edit tender-taussig-uc6y50

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

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.