Created
December 13, 2018 10:01
-
-
Save thysultan/60f33757e00b4d659f69a889b7188338 to your computer and use it in GitHub Desktop.
router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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