Table of Contents
You might have come across instances where you would want to include a third-party javascript directly in your react application, like including analytics script or some library directly from the CDN. In this article, we will see different ways to include JavaScript inside a react application.
index.html
Including the script in If you want the script to be loaded on every page of your application, you can directly add it to the index.html
as shown below:
1...2<script4 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"5 crossorigin="anonymous"6 async7></script>8...
If you run the application, inspect and check, you will see the script added inside the head
tag:
useEffect
Adding script using If you need to add a script to a specific component and after the component has mounted, you can have it inside the useEffect
hook:
1import { useEffect } from "react"2import { Helmet } from "react-helmet"34function App() {5 useEffect(() => {6 const script = document.createElement("script")78 script.src =1011 script.async = true1213 script.integrity =14 "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"1516 script.crossOrigin = "anonymous"1718 document.body.appendChild(script)1920 return () => {21 // clean up the script when the component in unmounted22 document.body.removeChild(script)23 }24 }, [])2526 return <div className="App"></div>27}2829export default App
If you want to reuse this snippet, then you can create a custom hook as shown below:
1import { useEffect } from "react"23const useScript = (url, integrity, async = true, crossOrigin = "anonymous") => {4 useEffect(() => {5 const script = document.createElement("script")67 script.src = url89 script.async = async1011 if (integrity) {12 script.integrity = integrity13 }1415 script.crossOrigin = crossOrigin1617 document.body.appendChild(script)1819 return () => {20 document.body.removeChild(script)21 }22 }, [url, integrity, async, crossOrigin])23}2425export default useScript
And use it in the App component as shown below:
1import useScript from "./useScript"23function App() {4 useScript(6 "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"7 )8 return <div className="App"></div>9}1011export default App
react-helmet
Adding script using There is a library called react-helmet, which can be used to add scripts as well.
First, let's install it using the following command:
1npm i react-helmet
It can be used to include script (or any element inside the head tag) as shown below:
1import { Helmet } from "react-helmet"23function App() {4 return (5 <>6 <Helmet>7 <script9 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"10 crossorigin="anonymous"11 async12 ></script>13 </Helmet>14 <div className="App"></div>15 </>16 )17}1819export default App
Do follow me on twitter where I post developer insights more often!