How to convert JSON to normal html with html elements in a react app?
Note that dangerouslySetInnerHTML can be dangerous if you do not know what is in the HTML string you are injecting
According to react docs -
dangerouslySetInnerHTML is React’s replacement for using innerHTML 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 out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
I have created a code sandbox below: https://codesandbox.io/s/relaxed-sunset-tlmr2?file=/src/App.js
The output just renders as string instead of html elements.
Here is my code:
import React from "react";
import "./styles.css";
const blocks = {
time: 1602725895949,
blocks: [
{
type: "header",
data: {
text: "This is a heading",
level: 2
}
},
{
type: "paragraph",
data: {
text: "This is a paragraph"
}
}
]
};
export default function App() {
function convertToHtml({ blocks }) {
console.log(blocks);
var convertedHtml = "";
blocks.map((block) => {
switch (block.type) {
case "header":
convertedHtml += `<h${block.data.level}>${block.data.text}</h${block.data.level}>`;
break;
case "paragraph":
convertedHtml += `<p>${block.data.text}</p>`;
break;
default:
console.log("Unknown block type", block.type);
break;
}
});
return <React.Fragment>{convertedHtml}</React.Fragment>;
}
return (
<div className="App">
<h1>JSON to html below</h1>
{convertToHtml(blocks)}
</div>
);
}