0

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

prashant
  • 210
  • 2
  • 11
  • you can use document.createElement to create a new script tag. And append it to the html when a certain component mounts – thealpha93 Jan 03 '21 at 14:08
  • can you describe in detail @thealpha93 – prashant Jan 03 '21 at 14:21
  • Does this answer your question? [How do I use external script that I add to react JS?](https://stackoverflow.com/questions/53396307/how-do-i-use-external-script-that-i-add-to-react-js) – fuggerjaki61 Jan 03 '21 at 15:50

2 Answers2

0

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

  • This answer is only minimal helpful. You could add an explanation or a little example to your answer to improve its quality. If you're doing it good enough, you may get some upvotes. Please see [answer] and edit your answer. – fuggerjaki61 Jan 03 '21 at 15:52
-1
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

thealpha93
  • 780
  • 4
  • 15
  • how to include the working of second script tag. Simply including them in above function is not working . @thealpha93 – prashant Jan 03 '21 at 14:56