Guim
Guim

Reputation: 678

Render script tag in React Component

I'm making a React application and I need to run a Javascript script only in one component, making reference to one of the div's.

I know there are some libraries to do so, but I wonder if there's a more direct way to do it. Right now I do this:

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

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

But nothing happens. The script is stored in public/js/myScript.js.
Thanks!

Upvotes: 11

Views: 25550

Answers (4)

AnWho
AnWho

Reputation: 1

You can also use a external component "Helmet" for implement script tags and you can also use link tag,meta tag,style tag etc with the help of this component.

Upvotes: 0

Arif Cemre
Arif Cemre

Reputation: 31

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>
        );
    }
}

Upvotes: 3

Guim
Guim

Reputation: 678

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.

Upvotes: 11

kev
kev

Reputation: 1031

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.

Upvotes: 4

Related Questions