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