Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Created February 11, 2017 15:27
Show Gist options
  • Save nicolasparada/bd89ff209bebc659f87c4606ef683d75 to your computer and use it in GitHub Desktop.
Save nicolasparada/bd89ff209bebc659f87c4606ef683d75 to your computer and use it in GitHub Desktop.
Preact router code splitting
import { Component, h } from 'preact'
import Router from 'preact-router'
import Nav from './components/nav.jsx'
const asyncComponent = getComponent => class extends Component {
componentWillMount() {
if (!this.state.component) {
getComponent()
.then(module => module.default)
.then(this.linkState('component'))
}
}
render(props, { component }) {
return component ? h(component, props) : null
}
}
const Home = asyncComponent(() => import('./pages/home.jsx'))
const About = asyncComponent(() => import('./pages/about.jsx'))
const Contact = asyncComponent(() => import('./pages/contact.jsx'))
const NotFound = asyncComponent(() => import('./pages/not-found.jsx'))
export default () => (
<div>
<Nav />
<Router>
<Home path="/" />
<About path="/about" />
<Contact path="/contact" />
<NotFound default />
</Router>
</div>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment