Adding Script Tag to React/Jsx

Adding script tag to React/JSX

Edit: Things change fast and this is outdated - see update


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

However, this is only really helpful if the script you want to load isn't available as a module/package. First, I would always:

  • Look for the package on npm
  • Download and install the package in my project (npm install typekit)
  • import the package where I need it (import Typekit from 'typekit';)

This is likely how you installed the packages react and react-document-title from your example, and there is a Typekit package available on npm.



Update:

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 makes it a great candidate for a custom hook (eg: hooks/useScript.js):

import { useEffect } from 'react';

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

script.src = url;
script.async = true;

document.body.appendChild(script);

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

export default useScript;

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
}

How to load custom script in react?

To add a random script like this, you could:

  1. Add the script to your index.html
  2. Paste the code to a file and use an import statement.
  3. Dynamically load the script once the user does something, using code splitting.

1. Adding the script to your HTML

Just stick the script tags in your index.html file, preferably at the end of the body tags. If using create-react-app, the index.html file is located in the public directory:

<body>
<div id="root"></div>
<script>/* your script here */</script>
</body>

2. Import from file

Alternatively, you could paste the script into a .js file, and import it from anywhere in your code. A good place to import general scripts would be in your index.js entry point file. This approach has the benefit of including the script with the rest of your js bundle, enabling minification and tree shaking.

// index.js
import "../path/to/your/script-file";

3. Code splitting
Lastly, if you would like to dynamically load a piece of js code in a certain point in time, while making sure it isn't part of your starting bundle, you could do code splitting, using dynamic imports. https://create-react-app.dev/docs/code-splitting

function App() {
function handleLoadScript() {
import('./your-script')
.then(({ functionFromModule }) => {
// Use functionFromModule
})
.catch(err => {
// Handle failure
});
};

return <button onClick={handleLoadScript}>Load</button>;
}

React update content of a script tag

Have you tried changing the parameters in the UseEffect itself? Something like

useEffect(()=>{

if (selectedFolderName) {
window.ac_vh_params = { containerId: 'container', folderName: '${selectedFolderName}' };
}
}
//... rest of code
)

Use JSX when using react loaded by <script> tag on html page

You need a transpiler, not a bundler. You can run one client-side, but shouldn't because it introduces performance problems (and can make it harder to debug your code).

This is covered in the documentation:

The quickest way to try JSX in your project is to add this <script>
tag to your page:

 <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

Now you can use JSX in any <script> tag by adding
type="text/babel" attribute to it. Here is an example HTML file with
JSX that you can download and play with.

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.



Related Topics



Leave a reply



Submit