Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS how to get script inside dangerouslySetInnerHTML executed

How to get script inside dangerouslySetInnerHTML get executed?

class Page extends Component {

  render() {
    return (
      <script
        dangerouslySetInnerHTML={{ __html: `
          console.log('hello world');
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({
            event: 'viewCart'
          });
        ` }}
      />
    );
  }
}

I can't get console.log('hello world') executed. Anybody can help? Thank you

like image 316
Kris MP Avatar asked Jun 14 '16 05:06

Kris MP


People also ask

HOW include external script in React?

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. Import 'ScriptTag' component: Import the built-in 'ScriptTag' component from the react-script-tag library at the top of the file where we want to add the script tag.

Does innerHTML work in React?

dangerouslySetInnerHTML is a property that you can use on HTML elements in a React application to programmatically set their content. Instead of using a selector to grab the HTML element, then setting its innerHTML , you can use this property directly on the element.

Is it good to use dangerouslySetInnerHTML?

Is it OK to use dangerouslySetInnerHTML? Yes, it will help you render markups in ways that the React JSX element will prohibit by default. It will help you pass HTML directly into a component within JSX.

How do you call a script in React?

Step 1: I installed React-Helmet using npm i react-helmet from the terminal while inside my react-app folder path. Step 2: I then added import {Helmet} from "react-helmet"; header in my code. Show activity on this post. To add script tag or code in head tag <head> , use react-helmet package.


1 Answers

Script elements don't get executed because of the way that react-dom creates them.

When ReactDOM.createElement receives a type of 'script' it uses .innerHTML instead of using document.createElement like you might expect.

var div = document.createElement('div');
div.innerHTML = '<script></script>';

var element = div.removeChild(div.firstChild);

Creating the script in this way sets the "parser-inserted" flag on that element to true. This flag tells the browser that it should not execute.


https://github.com/facebook/react/blob/c2a2d8a539bf02e40c43d36adc2826e228f30955/packages/react-dom/src/client/ReactDOMComponent.js#L406

https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations

https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0

like image 73
spencer.sm Avatar answered Sep 28 '22 18:09

spencer.sm