'What can I use instead of the JavaScript Function constructor to get my parsed function executed in React app
From api I get this HTML:
<div class="my-class" data-src="/event/66478667"></div>
<script>(function(d, s, id) {var js,ijs=d.getElementsByTagName(s)[0];if(d.getElementById(id))return;js=d.createElement(s);js.id=id;js.src="https://embed.widget.js";ijs.parentNode.insertBefore(js, ijs);}(document, 'script', 'my-js'));</script>
Now I am parsing this HTML through react-html-parser package like:
import parser, { Transform } from 'react-html-parser';
const transform: Transform = (node: { type: string; children: { data: string }[] }) => {
if (node.type === 'script' && node.children?.length) {
// eslint-disable-next-line no-new-func
Function(node.children[0].data)();
}
};
const options = {
transform,
};
return (
<div>
{parser(html, options)}
</div>
);
The HTML is containing a <script> with a function. But this <script> tag doesn't get executed in the React jsx, after parsed and rendered. The only way to get the widget to work, is when I use the JavaScript Function constructor (with an IIFE).
From Eslint I get: The Function constructor is eval.eslintno-new-func.
Is there maybe a better / more safe way to get this function executed in my React app, instead of using the JavaScript Function constructor?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
