Skip to content

Instantly share code, notes, and snippets.

@lsjroberts
Last active July 26, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsjroberts/55e79270b8cf6b26c43f5a335058f615 to your computer and use it in GitHub Desktop.
Save lsjroberts/55e79270b8cf6b26c43f5a335058f615 to your computer and use it in GitHub Desktop.
Dynamic loading helpers for React Router
const loadRoute = (next) =>
(module) =>
next(null, module.default);
const loadRoutes = (next) =>
(modules) =>
next(null, modules.map(module => module.default));
const loadRouteComponent = (importer) =>
(location, next) =>
importer()
.then(loadRoute(next))
.catch(console.error);
const route = (path, importer) => ({
path,
getComponent: loadRouteComponent(importer),
});
const routes = (config) =>
Object.keys(config).map(path =>
route(path, config[path])
);
export {
loadRoute,
loadRoutes,
loadRouteComponent,
route,
routes,
};
import { routes } from './route-helpers';
import App from './components/app';
const rootRoute = {
component: App,
childRoutes: routes({
'/': () => System.import('./home'),
about: () => System.import('./about'),
blog: () => System.import('./blog'),
}),
};
export default rootRoute;
@C3PablO
Copy link

C3PablO commented Jul 26, 2017

Thanks for this tip. I'm moving my applications to use this methodology but I'm facing a problem that I don't know how to solve. The static approach allows to do <IndexRedirect to="home" /> so when the user goes to / ends up at /home. Any idea how to do the "index redirect" with the dynamic-routes-object?

@C3PablO
Copy link

C3PablO commented Jul 26, 2017

Found the solution: indexRoute: { onEnter: (nextState, replace) => replace('/home') },

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