Skip to content

Instantly share code, notes, and snippets.

@Schniz
Last active August 25, 2016 05:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Schniz/7096536612e8a2151d81 to your computer and use it in GitHub Desktop.
Save Schniz/7096536612e8a2151d81 to your computer and use it in GitHub Desktop.
Async react router component for using webpack chunks like Instagram guys do. work in progress.
/** @jsx React.DOM */
var React = require('react');
var handlers = {};
var AsyncRoute = function(req) {
return React.createClass({
getInitialState: function() {
return {
myComponent: handlers[req]
};
},
statics: {
willTransitionTo: function (transition, params, query, callback) {
transition.wait(new Promise(function(resolve, reject) {
require.ensure([], function() {
var Comp = handlers[req] || require(req);
handlers[req] = Comp;
resolve();
});
}));
}
},
render: function() {
return (<this.state.myComponent />);
}
});
};
module.exports = AsyncRoute;

Usage

put it in your ./src/client stuff and then you can rock it with:

var routes = (
  <Route handler={ App } path="/">
    <DefaultRoute handler={ Home } />
    <Route handler={ AsyncRoute('./login-screen.js') } path="/login" />
    <Route handler={ AsyncRoute('./profile.js') } path="/profile/:user" />
  </Route>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment