1import { useEffect } from 'react';
2
3const useScript = url => {
4 useEffect(() => {
5 const script = document.createElement('script');
6
7 script.src = url;
8 script.async = true;
9
10 document.body.appendChild(script);
11
12 return () => {
13 document.body.removeChild(script);
14 }
15 }, [url]);
16};
17
18export default useScript;
19
1import React,{Component} from "react";
2import ReactDOM from "react-dom";
3
4import "./styles.css";
5
6class App extends Component {
7 componentDidMount() {
8 const script = document.createElement("script"); script.async = true; script.src = "https://some-scripturl.js"; this.div.appendChild(script); }
9 render() {
10 return (
11 <div className="App" ref={el => (this.div = el)}> <h1>Hello react</h1>
12 {/* Script is inserted here */}
13 </div>
14 );
15 }
16}
17
18export default App;