Issue
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.
Solution
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 />
.
Answered By – Phil
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0