0

I'm new to ReactTS. Now I need to insert a web page written in native JS and HTML into a react project.

The code is as follows:

export default class OpenDrive extends React.PureComponent {
    override componentDidMount() {
        const src1 = document.createElement('script');
        src1.type = 'text/javascript';
        src1.async = true;
        src1.src = './Viewer/ModuleOpenDrive.js';
        document.body.appendChild(src1);
    }

    override render() {
        return (
            <div style={{ height: '100%', width: '100%' }}>
                <div id="ThreeJS" style={{ height: '100%', width: '100%' }}></div>
                <div className="popup_info bottom_info" id="spotlight_info"></div>
                <input id="xodr_file_input" type="file" style={{ visibility: 'hidden' }} />
            </div>
        );
    }
}

The script tag has been successfully loaded on the browser, but with value $0. The script inserted in this way seems to only support JS code on the network, not local.

Is there any way for me to run local JS code here?

Azphire
  • 93
  • 1
  • 1
  • 7
  • 1
    Where are you placing the JS file? Also, are you using create-react-app? – Hoang Feb 28 '22 at 02:44
  • 1
    @Hoang. The JS file is in `./Viewer`, relative to the code file above. And, In fact I don't know if create-react-app is used in this project. It is a large project and was not written by me. :( I only know that it runs with `yarn web: serve`. – Azphire Feb 28 '22 at 03:04
  • 1
    I think the ModuleOpenDrive.js file pathe here is relative to current file but when it gets appended inside the body the src attribute has a path which does not exist in the DOM. So if the code in ModuleOpenDrive.js is not lengthy you can shift it to index.html in public folder inside a script tag. – Shubham Waje Feb 28 '22 at 05:06
  • @Shubham Yes you are right, the JS file cannot be accessed after compilation. Is there any other way to run local JS in ReactTS? – Azphire Feb 28 '22 at 06:56
  • 1
    It is difficult to answer without more details to your setup (like webpack, etc). But one way you can try is to use dynamic import: ``` import("./Viewer/ModuleOpenDrive.js"); ``` if your bundler supports it. However, be aware that the above or your current code will load the script multiple time (every time the component is mounted) – Hoang Feb 28 '22 at 10:28
  • @Hoang That helps a lot, thanks! However I have to solve new problem while running that imported code. Seems that create-react-app was not used, and it's hard to import static files now. – Azphire Mar 03 '22 at 02:10

0 Answers0