I'm still completely new to react. I tried creating in index.html file with the following contents:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Tutorial</title>
<!-- Not present in the tutorial. Just for basic styling. -->
<link rel="stylesheet" href="css/base.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js"></script>
</head>
<body id="html-body">
<div id="content"></div>
<script type="text/babel" src="scripts/box.js"></script>
<script type="text/babel">
ReactDOM.render(
<Box />,
document.getElementById('content')
);
</script>
</body>
</html>
And in scripts/box.js I have the following code:
var Box = React.createClass({
render: function() {
return (
<h2>Purple Monkey</h2>
);
}
});
When I view index.html in my browser, I get the error Uncaught ReferenceError: Box is not defined . But when i move the ReactDOM.render line in index.html into the scripts/box.js right after defining the Box class, everything works.
Why can't I execute the ReactDOM.render outside of scripts/box.js ? How do I properly include/require a react component so it can be used by other javascript files?
<script type="text/babel">tags get compiled under the hood, they might have their own scopes. As an experiment, does doingwindow.Box = React.createClasswork?var Box =withwindow.Box =, then everything works. How come that worked?text/babelcreates its own scope, like a function would wherevarsare only available inside the function's closure. This way of writing React is not meant for production, just for getting the hang of things. For now just put stuff in the same script tag and once you feel comfortable pull down a boilerplate and start coding from there like this one github.com/gaearon/react-hot-boilerplate