How to render html string including script tags in React

When we render normal html string(not including script tag) in react, we might use dangerouslySetInnerHTML. However, there is a risk to be exposed to XSS by this way. Moreover, it is impossible to render script tags. We have to consider another way.

How to do it

There is an example below. The variable ‘arrayIncludingHtml’ includes objects which have script tags.

import React, { useRef, useEffect } from 'react';export default function TopView({ arrayIncludingHtml }) {
const contentRef = useRef();

useEffect(() => {
arrayIncludingHtml.map(a => {
const fragment = document.createRange().createContextualFragment(
` <div>${a.content}</div>`, // a.content is html string including script tag
);
if (contentRef.current) {
contentRef.current.appendChild(fragment);
} else {
return;
}
});
});
return (
<div ref={contentRef} />
);
}

We can create DOM fragments with

createRange().createContextualFragment

Additionally, it is possible to insert the fragment into div tag in return with appendChild. Script tag would be rendered!

Started LinkedIn as well!

https://www.linkedin.com/in/tomoharu-tsutsumi-56051a126/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store