Reputation: 9080
I'm just learning reactjs - I'm going through the tutorials. What I can't figure out is why when I include my React script in the code it works (1st snippet). However, when I extract the script code into a separate .js file (2nd snippet) it doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
</script>
</body>
</html>
2nd Snippet:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
<script src="Scripts/custom/react.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
react.js file:
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
As a note, I've wrapped the above js file in the <script type="text/babel"></script>
and that didn't work either.
I've asked this in the Code Review site as well, however, I'm not sure if it belongs there or not.
As noted in a comment below, I do see a syntax error, highlighted on the <h1>Hello, world!</h1>,
line.
Upvotes: 1
Views: 98
Reputation: 57924
Try naming the file with the .jsx
extension, and with text/babel
type. You have to use the .jsx
extension for Babel to know how to transpile it, which loaders to use, etc. With your current .js
extension, Babel sees a regular JavaScript file and does not do anything, thus the error occurs. Also, include your custom script after your div
because React has to wait for root
to be loaded before it can insert anything -- and also, rename your file, it's quite confusing:
<div id="root"></div>
<script type="text/babel" src="Scripts/custom/react.jsx"></script>
Upvotes: 3