Reputation: 41
How can I split a string at its line breaks.
The Code below works fine. But I am looking for different solution without using "dangerouslySetInnerHTML".
Maybe someone knows.
<div> <div dangerouslySetInnerHTML={{__html: String.split("\n").join("<br />")}} </div>
Upvotes: 2
Views: 74
Reputation: 1379
You can use CSS to use white-space: pre;
, which will respect the line breaks in the text, within the targetted element.
.respect-line-breaks {
border: 1px solid #444;
white-space: pre;
}
<div class="respect-line-breaks">This
is
spread
over
multiple
lines
</div>
Is an example.
You can also use the HTML <pre>
tag, instead of a <div>
if you'd prefer, which negates the need for the CSS. <pre>
is also supported in much older browsers too, if that's something you need.
One thing to be aware of though is that if later on when developing your application, you loop through all of your <div>
elements, it won't pick up the <pre>
elements, which is why I would personally use the CSS solution, if at all possible.
This also means that you can use something like a <p>
tag, instead of a <div>
, and keep all your normal text styling, etc., in place.
Upvotes: 3