How to Load Script in React Component

How to load script in react component

After a lots of R&D finally I found my solution.

I have used npm postscribe to load script in react component

postscribe('#mydiv', '<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown"></script>')

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

How to load script in react js? script doesn't work

componentDidMount() lifecycle method is usually is used for fetching data from an API not for importing js file. Simply just import your script.js in Video.js. You should also export the functions you need in script.js and then you can call your functions in your class by adding the name you specified at the first. in code below I only export showFriendsFace() from script.js and called it in Video.js constructor:

import React from 'react';
import { Modal, Icon } from 'semantic-ui-react';
import Script from './script'


class Video extends React.Component {
constructor(){
super();

Script.showFriendsFace();
}

render() {
return (
//your return code
);
}
}

export default Video;

and script.js should look like this:

//your script codes

function showFriendsFace() {
console.log("Hello World!");
}

export default {showFriendsFace};

React load script on specfic div

You can use the custom hook:

import { useEffect } from 'react';

const useScript = (url, position, async = true) => {
useEffect(() => {
const placement = document.querySelector(position);
const script = document.createElement('script');

script.src = url;
script.async = typeof async === 'undefined' ? true : async;

placement.appendChild(script);

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

export default useScript;

Usage:

useScript(url, ".script-here");

Or just use dangerouslySetInnerHTML

<div className="script-here" dangerouslySetInnerHTML={{__html: your_script}} /> 


Related Topics



Leave a reply



Submit