Skip to content

Instantly share code, notes, and snippets.

@AlesRuzickaEu
Created August 9, 2018 08:32
Show Gist options
  • Save AlesRuzickaEu/04e64c7b69c84040eb9b035702ae17d9 to your computer and use it in GitHub Desktop.
Save AlesRuzickaEu/04e64c7b69c84040eb9b035702ae17d9 to your computer and use it in GitHub Desktop.
Hyperapp hash router
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