External js can not run in HTML

External js can not run in HTML
0

Hi
I was working with react, but when I use the following code, my external js can not run
But when i put the js code in HTML it is working
Could you help me ?
Thanks

…HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random_Quote</title>
</head>
<body>
    <div id="root1"></div>
    <div id="root"></div>

    <script type="text/babel">
        const JSX = (
          <div>
            <h1>Hello World</h1>
          </div>
        );
        ReactDOM.render(JSX, document.getElementById("root1"));
    </script>

    <script  type="text/javascript" src="Random_Quote.js" charset="utf-8"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</body>
</html>

…js

const JSX = (
  <div>
    <h1>Hello World</h1>
    <p>Lets render this to the DOM</p>
  </div>
);
// change code below this line
ReactDOM.render(JSX, document.getElementById("root"));

Hi,

What is the location of your .html and .js files? Are they located in the same directory?

Any script tags for your custom JS code need to be placed after the script tags for the React library files—i.e., React needs to be loaded before you can use it. Babel also needs to be loaded before you can use that.

1 Like

yes, they are in same directory, when I change js file as following , it’s working,

const JSX = (
          alert("hi")
        );
        ReactDOM.render(JSX, document.getElementById("root"));

HI , I have try several times but still not working

<body>
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
    <script  type="text/javascript" src="Random_Quote.js" charset="utf-8"></script>
</body>

Also, the following should go after the other scripts.

    <script type="text/babel">
        const JSX = (
          <div>
            <h1>Hello World</h1>
          </div>
        );
        ReactDOM.render(JSX, document.getElementById("root1"));
    </script>

Also, you might want to put the following script first:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>

If your Random_Quote.js file contains any JSX, it should have the text/babel type on it, instead of text/javascript.

Thanks, it solved my issue