- May 2022
-
betterprogramming.pub betterprogramming.pub
-
React Helmet
```js import {Helmet} from "react-helmet";
const Demo = props => ( <br /> <div className="application"> <Helmet> <script src="/path/to/resource.js" type="text/javascript" /> </Helmet> ... </div>
); ```
DOM Method
```js componentDidMount () { const script = document.createElement("script"); script.src = "/path/to/resource.js"; script.async = true; document.body.appendChild(script); }
export const appendScript = (scriptToAppend) => { const script = document.createElement("script"); script.src = scriptToAppend; script.async = true; document.body.appendChild(script); }
class Demo extends React.Component { componentDidMount () { appendScript("/path/to/resource.js"); } } ```
React Hooks
js useEffect(() => { const script = document.createElement('script'); script.src = "/path/to/resource.js"; script.async = true; document.body.appendChild(script); return () => { document.body.removeChild(script); } }, []);
```js import { useEffect } from 'react'; const importScript = resourceUrl=> { useEffect(() => { const script = document.createElement('script'); script.src = resourceUrl; script.async = true; document.body.appendChild(script); return () => { document.body.removeChild(script); } }, [resourceUrl]); };
const Demo = props => { importScript("/path/to/resource.js"); } ```
-
- Dec 2021
-
www.digitalocean.com www.digitalocean.com
-
css-tricks.com css-tricks.com