简体   繁体   中英

How to include external js files in an react component

I am trying to insert some external js files in my react component. I tried to include them in a simple html file in script tags and it was working fine but how to do in react component. How I included them in html page:-

<script src="js/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/eclipse");
    editor.session.setMode("ace/mode/c_cpp");
</script>
<body>
   <div id="editor">
       //text to display
   </div>
</body>

id="editor" is defined in js files which is included in the script tags so main problem is how to include this in a react component. I have seen some results showing to use customReactHooks but no idea how to implement it. Any idea

You can make use of npm library named react-script-tag

const loadScript = (callback) => {
  const script = document.createElement('script');
  script.src = 'path'; // path for your script
  script.id = 'some id';
  document.body.appendChild(script);

  script.onload = () => {
    if (callback) callback();
  };
}

call this function in the useEffect or componentDidMount of your react component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM