DCR
DCR

Reputation: 15665

react not loading external js file

Why does the first example work when the jsx script is inline but the second example not work:

UPDATE: both examples work when run off a server but only the first one works when run by just clicking on hello.html from the file system.

First Example:

<!DOCTYPE html>
<html>
  <head>
    <title>ReactJS Example</title>
    <script src='react/react.js'></script>
    <script src='react/react-dom.js'></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id='container'>
    </div>
    <script type='text.jsx'>             
      ReactDOM.render(
        <h1> Hello, React! </h1>,
        document.getElementById('container')
      );        
    </script>
  </body>
</html>

Second example:

<!DOCTYPE html>
<html>
  <head>
    <title>ReactJS Example</title>
    <script src='react/react.js'></script>
    <script src='react/react-dom.js'></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id='container'>
    </div>
    <script src='hello.js' type='text/jsx'></script>
  </body>
</html>

hello.js:

 ReactDOM.render(
        <h1> Hello, React! </h1>,
        document.getElementById('container')
      );   

Upvotes: 1

Views: 2894

Answers (2)

iSteven Zion
iSteven Zion

Reputation: 124

add these scripts in your head tag. I've just solved it now

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"> 
</script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react- 
dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

make sure your external js script type="text/babel"

Upvotes: 0

ArrowHead
ArrowHead

Reputation: 609

I think you have a typo in src. You should correct it src=>"hello.js"

change

<script src='hello'js' type='text.jsx'></script>

to

<script src='hello.js' type='text.jsx'></script>

Additionally, your script type should be

text/babel

Maybe this will help you :

https://medium.com/@to_pe/how-to-add-react-to-a-simple-html-file-a11511c0235f

Additionally , you might want to take a lookt at this: Single React Component rendering with Babel Standalone with only index.html and Component You might have to do a few corrections.

Upvotes: 1

Related Questions