How to render html string including script tags in React

Tomoharu Tsutsumi
1 min readFeb 14, 2021

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/

--

--

Tomoharu Tsutsumi

Senior Software Engineer at two industry-leading startups ( Go | Ruby | TypeScript | JavaScript | Gin | Echo | Rails | React | Redux | Next)