Skip to content

Instantly share code, notes, and snippets.

@Schniz
Last active Aug 25, 2016
Embed
What would you like to do?
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