Skip to content

Instantly share code, notes, and snippets.

@jamesseanwright
Created July 17, 2019 16:40
Show Gist options
  • Save jamesseanwright/7f4818892e9270bcc4793ec996357d09 to your computer and use it in GitHub Desktop.
Save jamesseanwright/7f4818892e9270bcc4793ec996357d09 to your computer and use it in GitHub Desktop.
Lazy route loading with React.lazy and Suspense
import * as React from 'react';
import Nav from './Nav.jsx';
import { Router } from './routing';
const routes = new Map<string, React.ComponentType>([
['/', () => <p>Pick an Ipsum!</p>],
['/lorem', React.lazy(() => import('./pages/Lorem'))],
['/bacon', React.lazy(() => import('./pages/Bacon'))],
['/hipster', React.lazy(() => import('./pages/Hipster'))],
['/office', React.lazy(() => import('./pages/Office'))],
]);
const paths = [...routes.keys(), '/missing'].slice(1);
const App = () => (
<Router routes={routes} initialPath="/" notFound={<p>Route not found</p>}>
{Page => (
<>
<Nav paths={paths} />
<React.Suspense fallback={<div className="loading-spinner" />}>
<Page />
</React.Suspense>
</>
)}
</Router>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment