Search code examples
javascriptreactjsweb-componentbabeljs

ReactJs + Babel - Defining components using separate files


Trying to create a component class with separate files

Index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <script src="../../assets/libs/react-0.13.3/build/react.js"></script>
    <script src="../../assets/libs/babel.min.js"></script>
  </head>
  <body>
    <section class="reactive"></section>
    <script type="text/babel" src="../../components/AppBar/NavBar.js"></script>
    <script type="text/babel">
      var
        reactiveNode = document.querySelector('.reactive');
      React.render( <NavBar value='hello world'/>, reactiveNode );
    </script>
  </body>
</html>

Navbar.js

var NavBar = React.createClass({
  render: function ()
  {
    return ( <h1>{this.props.value}</h1> );
  }
});

After run, i'm having the log:

XHR finished loading: GET "http://localhost:3000/app/components/AppBar/NavBar.js"

Uncaught ReferenceError: NavBar is not defined

Only works if create the class in the index.html file


Solution

  • The problem was with the scope of the variable.

    Solve by use

    window.NavBar = React.createClass({
       // ...
    });