Meteor, React, And React Router Revisited

Since my original post on using Meteor, React, and React Router, many things have changed in the past few months. Meteor 1.2 has been released and React is officially supported along with some other niceties for Meteor. Additionally, React Router has gone through a lot of API changes to where my original example no longer works.

The Easier Way to Get React Router

Thanks to Benoit Tremblay, it is much easier to get started using React Router in your Meteor applications. He created a React Router package on Atmosphere that takes care of all the nitty gritty work. To get started using his React Router package, simply run this command in the root directory of your Meteor app:

meteor add reactrouter:react-router

Here's a simple example router using this package:

if(Meteor.isClient){
  const {
    Router,
    Route,
    IndexRoute,
    Link,
    history
  } = ReactRouter;

  // A history object must be created to maintain the history for our router
  const browserHistory = history.createHistory();

  // A basic app container where views will be rendered in
  App = React.createClass({
    getInitialState: function() {
      return {};
    },
    render: function() {
      return (
        <div>
          {this.props.children}
        </div>
      );
    }
  });

  // The view to displayed as the index view
  Index = React.createClass({
    getInitialState: function() {
      return {};
    },
    render: function() {
      return (
        <div>
          <p>This is the index route.</p>
          <Link to="/foo">Show me your foo.</Link>
        </div>
      );
    }
  });

  // A view for a route
  Foo = React.createClass({
    getInitialState: function() {
      return {};
    },
    render: function() {
      return (
        <div>
          <p>This is my foo.</p>
          <Link to="/">Now go home</Link>
        </div>
      );
    }
  });

  // The component with all of the routes
  Routes = React.createClass({
    getInitialState: function() {
      return {};
    },
    render: function() {
      return (
        <Router history={browserHistory}>
          <Route path="/" component={App}>
            <IndexRoute component={Index}/>
            <Route path="foo" component={Foo}/>
          </Route>
        </Router>
      );
    }
  });

  // Now render it
  $(document).ready(function() {
    React.render(<Routes/>, document.body);
  });
}

Wrap Up

It's way easier to use React Router now using by using the reactrouter:react-router package courtesy of Benoit Tremblay. As such, I've update my demo to use this package and use a little more functionality with React Router than previously shown.

#meteor.js   •   #react.js   •   #react-router