Reputation: 121
I am dynamically appending scripts to my react app like this
export const appendScript = (scriptToAppend : string) => {
const script = document.createElement("script");
script.src = scriptToAppend;
script.async = true;
script.type = "text/jsx";
document.body.appendChild(script);
}
App Component
class App extends React.Component {
componentDidMount() {
appendScript("./assets/custom.min.js");
}
}
custom.min.js file
$(document).ready(function(){
alert("ready");
})
Upvotes: 1
Views: 1995
Reputation: 11
import React, {useEffect} from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HomePage from "./Components/Home/HomePage";
function App(){
useEffect(() => {
const script = document.createElement("script");
script.src = "/js/main.js"; //your path to your file inside your public folder
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);` return( {/* this should work */} <Route path="/" element={} /> ) }
Upvotes: 0
Reputation: 41
Check the answer in https://stackoverflow.com/a/34425083/13558764.
Or you can try "react-helmet" package.
Here is a sample usage.
import React from "react";
import {Helmet} from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<script src="https://use.typekit.net/foobar.js"></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
</Helmet>
</div>
);
}
};
Upvotes: 1