I have an online letter template that I want to display ask text in my reactApp
My email is formatted with paragraphs and bold headings. How can I integrate the same formatting into React without having to use bruteforce and including a lot of tags.
I tried using a template literal to preserve the formatting but it does not work.
As Joseph stated in the comments, you can use dangerouslySetInnerHTML to render a string of HTML.
Example: code-sandbox
export default function App() {
const htmlString = "<h1>Hello world</h1>";
return (
<>
<div dangerouslySetInnerHTML={{ __html: htmlString }}></div>
</>
);
}
However, it's important to be aware of the security risks as the documentation states:
dangerouslySetInnerHTML
is React’s replacement for usinginnerHTML
in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type outdangerouslySetInnerHTML
and pass an object with a__html
key, to remind yourself that it’s dangerous.
Source: https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml