I am adding this script-tag to my React jsx render:
<script>alert('Hello world')</script>
Why is the Javascript code <script>alert('Hello world')</script>
not executing in my React app?
Update:
I am debugging this because I get this HTML back from api:
<div 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 html-react-parser package like:
return <div data-testid="html-paragraph">{parser(html)}</div>;
But this isn't working because the Javascript code isn't executing?
How to solve this?
See here my code sandbox.
CodePudding user response:
Remove the <script>
tag and replace with {}
.
So: {alert('Hello world')}
CodePudding user response:
You can add it via npm package. I used it as ( once ):
import React, { Component } from 'react';
import ScriptTag from 'react-script-tag';
class Demo extends Component {
render() {
return (<ScriptTag isHydrating={true} type="text/javascript" src="some_script.js" />);
}
}
Here is the npm package link https://www.npmjs.com/package/react-script-tag