If you want to render HTML code stores as a string in a string variable, first, you have to convert that string to HTML. I discuss two ways to convert strings to HTML in this article.
Here is an example of what happens if I render HTML stored in a string variable. The content displays as it is. That is similar to Javascript's innerText method.
import { useEffect, useState } from "react";
export const StringToHtml = () =>{
const [html, setHtml] = useState<string>("")
useEffect(() => {
setHtml("<div>Html stored as a string</div>")
}, [html])
return(
<div>{html}</div>
)
}
However, React Js does this on purpose. It prevents XSS (cross-site scripting). Therefore, React Js designers named the method that allows you to parse a string to HTML as dangerouslySetInnerHTML. Here is how to use it. Do not use dangerouslySetInnerHTML to render HTML sourced from untrusted sources. They can contain XSS that targets the end user.
import { useEffect, useState } from "react";
export const StringToHtml = () =>{
const [html, setHtml] = useState<string>("")
useEffect(() => {
setHtml("<div >Html stored as a string</div>")
}, [html])
return(
<div dangerouslySetInnerHTML={{__html: html}}></div>
)
}
If you need more features such as conditional rendering, appending, replacing, etc., the html-react-parser NPM package can handle most of them.
Add the package:
or
import { useEffect, useState } from "react";
import parse from 'html-react-parser';
export const StringToHtml = () =>{
const [html, setHtml] = useState<string>("")
useEffect(() => {
setHtml("<div>Html stored as a string</div>")
}, [])
return(
<>
{parse(html)}
</>
)
}