Skip to content

Instantly share code, notes, and snippets.

@neekey
Created June 26, 2016 04:17
Show Gist options
  • Save neekey/df2db56454cdb391510b585b0678b7e4 to your computer and use it in GitHub Desktop.
Save neekey/df2db56454cdb391510b585b0678b7e4 to your computer and use it in GitHub Desktop.
React-router-lazy-load-component
// @link https://github.com/reactjs/react-router/blob/v0.13.3/examples/partial-app-loading/app.js
var React = require('react');
var Router = require('react-router');
var { Route, RouteHandler, Link } = Router;
var AsyncElement = {
loadedComponent: null,
load: function () {
if (this.constructor.loadedComponent)
return;
this.bundle(function (component) {
this.constructor.loadedComponent = component;
this.forceUpdate();
}.bind(this));
},
componentDidMount: function () {
setTimeout(this.load, 1000); // feel it good
},
render: function () {
var Component = this.constructor.loadedComponent;
if (Component) {
// can't find RouteHandler in the loaded component, so we just grab
// it here first.
this.props.activeRoute = <RouteHandler/>;
return <Component {...this.props}/>;
}
return this.preRender();
}
};
var PreDashboard = React.createClass({
mixins: [ AsyncElement ],
bundle: require('bundle?lazy!./dashboard.js'),
preRender: function () {
return <div>Loading dashboard...</div>;
}
});
var PreInbox = React.createClass({
mixins: [ AsyncElement ],
bundle: require('bundle?lazy!./inbox.js'),
preRender: function () {
return <div>Loading inbox...</div>;
}
});
var App = React.createClass({
render: function () {
return (
<div>
<h1>Partial App</h1>
<ul>
<li><Link to="dashboard">Dashboard</Link></li>
</ul>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route handler={App}>
<Route name="dashboard" path="dashboard" handler={PreDashboard}>
<Route name="inbox" path="dashboard/inbox" handler={PreInbox}/>
</Route>
</Route>
);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.getElementById('example'));
});
@przeor
Copy link

przeor commented Sep 1, 2016

Hi I see that you use React, so I am sure that you will find interesting the https://reactjs.co - this is the free online convention and tutorial book for React.JS Developers. React is not only the View (in MVC) anymore. ReactJS For Dummies: Why & How to Learn React Redux, the Right Way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment