How to load script in react component

前端 未结 5 1811
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-29 16:45

I am having following script file



        
相关标签:
5条回答
  • 2020-12-29 17:06

    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>')
    
    0 讨论(0)
  • 2020-12-29 17:14

    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');
      }
    
    0 讨论(0)
  • 2020-12-29 17:14

    You can follow my answer over here: add third-party js library to Create React App

    0 讨论(0)
  • 2020-12-29 17:18

    I recommend using React Helmet. I've used it on a couple of Create-React-Apps, and it allows you to write actual script tags combined with vanilla JS.

    It makes the process a lot smoother. So for you it'd be something like this once you've imported React Helmet.

    <script language="javascript" src='http://tickettransaction.com/?bid='+ bid + '&sitenumber='+ site +'&tid=event_dropdown' ></ script>
    
    0 讨论(0)
  • 2020-12-29 17:21

    This came to my rescue. This is the easiest way to load Script Tags

    https://www.npmjs.com/package/react-script-tag

    import ScriptTag from 'react-script-tag';
    
    const Demo = props => (
    <ScriptTag src="/path/to/resource.js" />
    );
    

    There are other ways to do this too :

    https://medium.com/better-programming/4-ways-of-adding-external-js-files-in-reactjs-823f85de3668

    0 讨论(0)
提交回复
热议问题