Render script tag in React Component

By using dangerouslySetInnerHTML you can add any valid html you want to your elements.

import React, { Component } from "react";
import "../ThisComponent.css";

export default class MyComponent extends Component {
  render() {
    return (
      <div dangerouslySetInnerHTML="<script src='js/myScript.js' />" >
        <div id="scriptTarget" />
        <div className="main">
          // Other stuff
        </div>
      </div>
    );
  }
}

I should mention though that as the attribute name suggest, its use is strongly discouraged.


I finally solved it by adding the componentDidMount function before rendering the component. Like this:

import React, { Component } from "react";
import "../ThisComponent.css";

export default class MyComponent extends Component {
  componentDidMount() {
    const script = document.createElement("script");

    script.src = "js/myScript.js";
    script.async = true;

    document.body.appendChild(script);
  }

  render() {
    return (
      <div>
        <div id="scriptTarget" />
        <div className="main">
          // Other stuff
        </div>
      </div>
    );
  }
}

If somebody has a better solution please feel free to share it. I'll be aware to further recomendations.


export default class MyComponent extends Component {
    componentDidMount() {
        const script = document.createElement("script");
        script.innerHTML = "window.onload = function() {\n" +
            ...
            "}"
        script.async = true;
        document.body.appendChild(script);
    }

    render() {
        return (
            <div>
            </div>
        );
    }
}