Skip to content

Instantly share code, notes, and snippets.

@thysultan
Created December 13, 2018 10:01
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 thysultan/60f33757e00b4d659f69a889b7188338 to your computer and use it in GitHub Desktop.
Save thysultan/60f33757e00b4d659f69a889b7188338 to your computer and use it in GitHub Desktop.
router
<script type="module">
import {h, render} from '//unpkg.com/dyo?module'
function handleLocation ({href} = location, {origin} = location) {
return href.replace(origin, '')
}
function handleClick (event, {href, children}, state, context) {
context.forceUpdate(history.pushState(event.preventDefault(), document.title = children, href))
}
function Link ({href, children}) {
return h('a', {href, onClick: handleClick}, children)
}
function Route ({path, children}, state, {href}) {
return path === href ? children : null
}
function Router ({children}) {
return children
}
Router.getChildContext = function () {
return Object.create(this, {href: {get: handleLocation}})
}
// example use
render(h(Router,
h('nav',
h(Link, {href: '/'}, 'Home'),
h(Link, {href: '/?about'}, 'About'),
h(Link, {href: '/?contact'}, 'Contact')
),
h('main',
h(Route, {path: '/'}, 'Home'),
h(Route, {path: '/?about'}, 'About'),
h(Route, {path: '/?contact'}, 'Contact')
)
), document.body)
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment