Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React class is not defined (text/babel)

I have commentBox.jsx file, with following code:

var CommentBox = React.createClass( {
  render: function () {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
      </div>
    );
  }
});

In index.html, I want to render this component:

<div id="content"></div>
<script type="text/babel" src="scripts/commentBox.jsx"></script>

<script type="text/babel">
    ReactDOM.render(<CommentBox />, document.getElementById( 'content' ) );
</script>

But I'm getting error: "CommentBox is not defined"; Why this is not working? If I will place all code in one file(commentBox.js) - it will work.

like image 403
Andrey Avatar asked Dec 09 '15 11:12

Andrey


People also ask

What is Babel in ReactJS?

ReactJS | Introduction to Babel. Babel is a very famous transpiler that basically allows us to use future JavaScript in today’s browsers. In simple words, it can convert the latest version of JavaScript code into the one that the browser understands.

Why does Babel return a new class when transpiling?

Babel transpiles classes using SuperClass.apply (/* ... */), but native classes aren't callable and thus throw in this case. Some built-in functions (like Array) always return a new object. Instead of returning it, Babel should treat it as the new this.

Can you have a text node under a view in React Native?

In React Native, we are more strict about it: you must wrap all the text nodes inside of a <Text> component. You cannot have a text node directly under a <View>. You also lose the ability to set up a default font for an entire subtree.

Why do we need to wrap the Super class in Babel?

When extending a native class (e.g., class extends Array {} ), the super class needs to be wrapped. This is needed to workaround two problems: Babel transpiles classes using SuperClass.apply (/* ... */), but native classes aren't callable and thus throw in this case. Some built-in functions (like Array) always return a new object.


1 Answers

You need to declare var CommentBox; in its own script block above the other two. The scope of your variables is not shared between your script imports.

<div id="content"></div>
<script>
  var CommentBox;
</script>
<script type="text/babel" src="scripts/commentBox.jsx"></script>
<script type="text/babel">
  ReactDOM.render(<CommentBox />, document.getElementById( 'content' ) );
</script>

You can also remove the var from your jsx file.

like image 132
mitchfuku Avatar answered Oct 03 '22 08:10

mitchfuku