I am attempting to render an address from my model. The string contains line breaks that I am replacing with a break tag. Although, it is rendering on the page as a string instead as HTML. How can I force my string to render as HTML instead?
Attempt:
<span id="addressLine"> @Model.MyData.Address.Replace("\r\n", "<br />"); </span>
Result on page:
Address Top<br />Street Name<br />City<br />PostCode
Should be displayed as:
Address Top Street Name City PostCode
To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).
You can use the Html. Raw() method for that.
Unlike most HTML parsers which generate tree structures, HTMLString generates a string of characters each with its own set of tags. This flat structure makes it easy to manipulate ranges (for example - text selected by a user) as each character is independent and doesn't rely on a hierarchical tag structure.
React renders HTML to the web page by using a function called ReactDOM. render() .
Use @Html.Raw(Model.MyData.Address.Replace("\r\n", "<br />"))
Use
@(new HtmlString(@Model.MyData.Address))
It is safer, so that you avoid potential xss attacks
See this post: Rendering HTML as HTML in Razor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With