Created
August 9, 2018 08:32
-
-
Save AlesRuzickaEu/04e64c7b69c84040eb9b035702ae17d9 to your computer and use it in GitHub Desktop.
Hyperapp hash router
This file contains 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
import { h } from 'hyperapp' | |
const location = { | |
state: { | |
hash: window.location.hash | |
}, | |
actions: { | |
changed: () => () => { | |
return { hash: window.location.hash } | |
}, | |
go: (goTo) => () => { | |
window.location.hash = goTo | |
} | |
}, | |
subscribe: (routerActions) => { | |
window.addEventListener('hashchange', () => routerActions.changed()) | |
} | |
} | |
const Route = ({ path, render }) => { | |
const currentHash = window.location.hash || "#" | |
const match = currentHash.match(`^${path}$`) | |
if (match) { | |
return render({ path: currentHash, match }) | |
} | |
} | |
const Redirect = ({ to }) => { | |
window.location.hash = to | |
} | |
const Switch = (props, children) => children.find(a => a) | |
const Link = (props, children) => h('a', { ...props, href: props.to }, children) | |
export { location, Route, Redirect, Switch, Link } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment