0

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 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 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.

meez
  • 3,783
  • 5
  • 37
  • 91
  • You should be using curlybraces { /* code here */} instead. If you really want to use script tags, then you can use [reacthelmet](https://github.com/nfl/react-helmet) to do that. – Nils Kähler Mar 17 '22 at 13:16
  • 1
    Does this answer your question? [React: Script tag not working when inserted using dangerouslySetInnerHTML](https://stackoverflow.com/questions/35614809/react-script-tag-not-working-when-inserted-using-dangerouslysetinnerhtml) – Giovanni Esposito Mar 17 '22 at 13:16
  • It is really not recommanded to do that. Because this will pop an alert Window each time the component is re-rendered. And depending on your whole applications, renders may happen very often! – Ricola3D Mar 17 '22 at 13:17
  • What are you trying to do? What are you expecting to happen? – Guillaume Brunerie Mar 17 '22 at 13:22
  • In your sandbox you are missing closing parentheses on `{alert('Hello world')}` – semperlabs Mar 17 '22 at 13:41

2 Answers2

0

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

Asad Ashraf
  • 1,425
  • 8
  • 19
-1

Remove the <script> tag and replace with {}.

So: {alert('Hello world')}

Samball
  • 623
  • 7
  • 22