adding script tag to react/jsx

  • Last Update :
  • Techknowledgy :

To add script tag or code in head tag <head>, use react-helmet package. it is light and have good documentation. Step 2: I then added import {Helmet} from "react-helmet"; header in my code. For how to use script tags in React check some other answers on this page. (For my use case the script needed to live in head which is reflected here as well):

This is our Splunktool team suggestion ✌, we tried and its working fine
componentDidMount() {
   const script = document.createElement("script");​
   script.src = "https://use.typekit.net/foobar.js";
   script.async = true;​
   document.body.appendChild(script);
}

Do you want to fetch and execute the script again and again, every time this component is rendered, or just once when this component is mounted into the DOM?

Perhaps try something like this:

componentDidMount() {
   const script = document.createElement("script");

   script.src = "https://use.typekit.net/foobar.js";
   script.async = true;

   document.body.appendChild(script);
}

Now that we have hooks, a better approach might be to use useEffect like so:

useEffect(() => {
   const script = document.createElement('script');

   script.src = "https://use.typekit.net/foobar.js";
   script.async = true;

   document.body.appendChild(script);

   return () => {
      document.body.removeChild(script);
   }
}, []);

Which can be used like so:

import useScript from 'hooks/useScript';

const MyComponent = props => {
   useScript('https://use.typekit.net/foobar.js');

   // rest of your component
}

My favorite way is to use React Helmet – it's a component that allows for easy manipulation of the document head in a way you're probably already used to.

e.g.

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>
    );
  }
};

Suggestion : 2

Adding script using useEffect Adding script using react-helmet 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. If you need to add a script to a specific component and after the component has mounted, you can have it inside the useEffecthook:

1._
1...2<script3 src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" 4 integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" 5 crossorigin="anonymous" 6 async7>
   </script>8...
2._
1import { useEffect } from "react"2import { Helmet } from "react-helmet"3
4function App() {5  useEffect(() => {6    const script = document.createElement("script")7
8    script.src =9      "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"10
11    script.async = true12
13    script.integrity =14      "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"15
16    script.crossOrigin = "anonymous"17
18    document.body.appendChild(script)19
20    return () => {21      // clean up the script when the component in unmounted22      document.body.removeChild(script)23    }24  }, [])25
26  return <div className="App"></div>27}28
29export default App
3._
1
import {
   useEffect
} from "react"
2
3
const useScript = (url, integrity, async = true, crossOrigin = "anonymous") => {
   4 useEffect(() => {
      5
      const script = document.createElement("script") 6
      7 script.src = url8
      9 script.async = async10
      11
      if (integrity) {
         12 script.integrity = integrity13
      }
      14
      15 script.crossOrigin = crossOrigin16
      17 document.body.appendChild(script) 18
      19
      return () => {
         20 document.body.removeChild(script) 21
      }
      22
   }, [url, integrity, async, crossOrigin]) 23
}
24
25
export default useScript
5._
1n pm i react - helmet
6._
1import { Helmet } from "react-helmet"2
3function App() {4  return (5    <>6      <Helmet>7        <script8          src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"9          integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"10          crossorigin="anonymous"11          async12        ></script>13      </Helmet>14      <div className="App"></div>15    </>16  )17}18
19export default App

Suggestion : 3

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: If you run the application, inspect and check, you will see the script added inside the head tag: 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.

1._
...
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" async></script>
...
2._
import { useEffect } from "react"
import { Helmet } from "react-helmet"

function App() {
  useEffect(() => {
    const script = document.createElement("script")

    script.src =
      "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"

    script.async = true

    script.integrity =
      "sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"

    script.crossOrigin = "anonymous"

    document.body.appendChild(script)

    return () => {
      // clean up the script when the component in unmounted
      document.body.removeChild(script)
    }
  }, [])

  return <div className="App"></div>
}

export default App
3._
import {
   useEffect
} from "react"

const useScript = (url, integrity, async = true, crossOrigin = "anonymous") => {
   useEffect(() => {
      const script = document.createElement("script")

      script.src = url

      script.async = async

      if (integrity) {
         script.integrity = integrity
      }

      script.crossOrigin = crossOrigin

      document.body.appendChild(script)

      return () => {
         document.body.removeChild(script)
      }
   }, [url, integrity, async, crossOrigin])
}

export default useScript
5._
npm i react - helmet
6._
import { Helmet } from "react-helmet"

function App() {
  return (
    <>
      <Helmet>
        <script
          src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
          integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
          crossorigin="anonymous"
          async
        ></script>
      </Helmet>
      <div className="App"></div>
    </>
  )
}

export default App

Suggestion : 4

This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production. When you’re ready to move forward, remove this new <script> tag and the type="text/babel" attributes you’ve added. Instead, in the next section you will set up a JSX preprocessor to convert all your <script> tags automatically. First, open the HTML page you want to edit. Add an empty <div> tag to mark the spot where you want to display something with React. For example: We gave this <div> a unique id HTML attribute. This will allow us to find it from the JavaScript code later and display a React component inside of it.

1._
<!-- ... existing HTML ... -->

<div id="like_button_container"></div>
<!-- ... existing HTML ... -->
2._
  <!-- ... other HTML ... -->

  <!-- Load React. -->
  <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
  <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
  <!-- Load our React component. -->
  <script src="like_button.js"></script>
  </body>
3._
// ... the starter code you pasted ...

const domContainer = document.querySelector('#like_button_container');
const root = ReactDOM.createRoot(domContainer);
root.render(e(LikeButton));
5._
const e = React.createElement;

// Display a "Like" <button>
return e(
  'button',
  { onClick: () => this.setState({ liked: true }) },
  'Like'
);
6._
// Display a "Like" <button>
return (
  <button onClick={() => this.setState({ liked: true })}>
    Like
  </button>
);

Suggestion : 5

Adding a new script tag and directly appending it to the <head> element of the page is the easiest way to add <script> tags in the React app. react-helmet is a third-party library that can be used to achieve the same thing by handling the <head> tag on every page. The simplest solution is to add scripts directly into DOM using the Document interface provided by web APIs. We can use JavaScript's DOM manipulation methods to inject the <script> tag without React DOM interfering. A new script is appended to the head of the page whenever the component is mounted in the DOM. The script is removed when the component unmounts.

Custom hooks are usually stored in a separate directory within the /src folder. Let's create a new file inside the /src/hooks/ directory and name it useExternalScripts.js. Paste the following code in the file:

import {
   useEffect
} from 'react';

export default function useExternalScripts({
   url
}) {
   useEffect(() => {
      const head = document.querySelector("head");
      const script = document.createElement("script");

      script.setAttribute("src", url);
      head.appendChild(script);

      return () => {
         head.removeChild(script);
      };
   }, [url]);
};

In a component where you want to add a new script, paste the following code:

import useExternalScripts from "./hooks/useExternalScripts"

const Component = () => {
   useExternalScripts("https://www.scriptdomain.com/script")
      ...
}

Alternatively, you can use react-helmet, which manages changes within the <head> tag. The <Helmet> can take care of the script if it is placed inside of it.

import { Helmet } from "react-helmet"

export default function Component() {
  return (
    <>
      <Helmet>
        <script
          src="https://www.myscripts.com/scripts"
          crossorigin="anonymous"
          async
        ></script>
      </Helmet>
      ...
    </>
  )
}

Suggestion : 6

This is the first method and the method with the least complexity as well. The react-script-tag is a package that comes up with a <script> tag that supports universal rendering. With the help of this library, we can directly append the <script> tag to our document. And inside the ‘src’ attribute of the script tag, we can include the URL of the external JavaScript library.  Import ‘ScriptTag’ component: Import the built-in ‘ScriptTag’ component from the react-script-tag library at the top of the file where we want to add the script tag. Call this component inside our JSX component named ‘App’ and create a basic HTML <script> tag inside it. Into the <script> tag add the URL of the jQuery library with the ‘src’ attribute.

Step 1: Create a React application using the following command inside your terminal or command prompt:

npx create - react - app name_of_the_app

Step 2: After creating the react application move to the directory as per your app name using the following command:

cd name_of_the_app

Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package.

npm install--save react - script - tag

Call the <ScriptTag> component inside our App.js

import React from 'react';
import './App.css';
import ScriptTag from 'react-script-tag';
  
function App() {
  
  return (
    <div className='App'>
      <h1>Pretagcodeforgeeks : How to include an external 
      JavaScript library to ReactJS?</h1>
      <ScriptTag isHydrating={true} type="text/javascript" 
      src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" />
    </div>
  );
}
  
export default App;

Run the Application: Open the terminal and write the following command in your terminal.

npm start

Suggestion : 7

Client rendering correctly appends the script tag to the page github.com/adam-26/react-script-tag#readme A React <script> tag that supports universal rendering npm i react-script-tag

1._
npm install--save react - script - tag
2._
yarn add react - script - tag
3._
import React, { Component } from 'react';import ScriptTag from 'react-script-tag'class Demo extends Component {     render() {        return (<ScriptTag isHydrating={true} type="text/javascript" src="some_script.js" />);    }}