Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load script in react component

I am having following script file

<script language="javascript">

document.write('<script language="javascript" src="http://tickettransaction.com/?bid='+bid+'&sitenumber='+site+'&tid=event_dropdown" ></' + 'script>');
</script>

I follow this Adding script tag to React/JSX but it does not work for me...

How do I load the script in my react component?

like image 748
Ashh Avatar asked Apr 16 '18 06:04

Ashh


People also ask

How do I load a script into React component?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.

How do I load a script asynchronously in React?

Ideally, we'd like to load the scripts asynchronously, aka. in a non-blocking manner. What we can use the async and defer attributes on the script tag as per the MDN Doc says: async : If the async attribute is present, then the script will be fetched in parallel to parsing and evaluated as soon as it is available.

How import JavaScript file into React?

To import a component from another file in React:Export the component from file A , e.g. export function Button() {} . Import the component in file B as import {Button} from './another-file' . Use the imported component in file B .


2 Answers

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>')
like image 101
Ashh Avatar answered Oct 05 '22 16:10

Ashh


the following method is worked for me. try, hope it will work for you. basically, you can create a script tag and append it to the body tag. like this--

var tag = document.createElement('script');
tag.async = true;
tag.src = 'THE PATH TO THE JS FILE OR A CDN LINK';
var body = document.getElementsByTagName('body')[0];
body.appendChild(tag);

you can use this on a life cycle hook of react like this.

componentDidMount() {
    var loadScript = function (src) {
      var tag = document.createElement('script');
      tag.async = false;
      tag.src = src;
      var body = document.getElementsByTagName('body')[0];
      body.appendChild(tag);
    }

    loadScript('PATH TO THE JS FILE OR CDN URL');
  }
like image 39
Sushil Avatar answered Oct 05 '22 17:10

Sushil