Completely replace dangerouslySetInnerHTML to render dynamic HTML and CSS in React
npm install react-dynamic-renderTo render external HTML in React, the only way is “dangerouslySetInnerHTML” which as the name suggests can be dangerous as it makes your code vulnerable to cross-site scripting (XSS) attacks.
react-dynamic-render has zero-dependency only react as peer-dependency, making it very light. Completely eliminating the use of “dangerouslySetInnerHTML” and using React.createElement function to render HTML and CSS. With additional script to eliminate any kind of script or dangerous element/attributes.
``bash`
npm install react-dynamic-render
js
import React from "react";
import {
DynamicRenderJson,
htmlReactParser,
DynamicRender,
vNodeToHtmlString,
} from "react-dynamic-render";const PComponent = ({ text }) => {
return
{text}
;
};const html =
;const index = () => {
const htmlJson = htmlReactParser({ htmlString: html });
console.log("htmlJson", htmlJson);
// htmlJson {type: 'div', props: {…}}
const htmlString = vNodeToHtmlString({
htmlJson,
customComponents: { // CustomComponents is not mandatory
CustomComponent: PComponent,
},
});
console.log("htmlString", htmlString);
// htmlString
Testing React Dynamic Render (react-dynamic-render)
Hello World
return (
htmlJson={htmlJson}
customComponents={{ // CustomComponents is not mandatory
CustomComponent: PComponent,
}}
/>
htmlString={htmlString}
customComponents={{ // CustomComponents is not mandatory
CustomComponent: PComponent,
}}
/>
);
};export default index;
`
> customComponents` can be used to add more functionality to it