Skip to content

Instantly share code, notes, and snippets.

@danieldunderfelt
Created May 5, 2017 06:41
Show Gist options
  • Save danieldunderfelt/d0dc49f9e83cbdde0cc4a3eb7bcbdfa9 to your computer and use it in GitHub Desktop.
Save danieldunderfelt/d0dc49f9e83cbdde0cc4a3eb7bcbdfa9 to your computer and use it in GitHub Desktop.
A router based on hashrouter that uses the history api where available.
/**
This router depends on the history package:
yarn add history
Simple router for switching between routes. Based on
[hashrouter.js](https://gist.github.com/danieldunderfelt/4d016333a947764c1a5687d26d48ca27)
Suitable for MobX/Redux architecture and especially
handy for tabs, which is the reason why it exists.
const state = { currentTab: 'lions' }
function activateTab(tabName) {
// Dispatch state change
state.currentTab = tabName
}
// Instantiate a router and set the index route
// which is what get() will return when the hash is empty.
const router = historyrouter('lions')
router.listen(activateTab)
<TabBar
tabs={[
{ name: 'lions', label: 'Lions' },
{ name: 'tigers', label: 'Tigers' }
]}
onSelect={ tab => router.go(tab.name) }
selectedTab={ state.currentTab } />
**/
const listeners = []
let createHistory, usesHistory = 'browser'
if( window.history && window.history.pushState ) {
createHistory = require('history/createBrowserHistory').default
} else {
usesHistory = 'hash'
createHistory = require('history/createHashHistory').default
}
const history = createHistory()
export default (index = '/') => {
function go(toRoute, replace = false) {
if(replace) {
history.replace(toRoute)
} else {
history.push(toRoute)
}
notifyListeners()
return get()
}
function get() {
const locString = usesHistory === 'hash' ?
window.location.hash :
window.location.pathname
const sliceStart = usesHistory === 'hash' ? 2 : 1
const current = locString.slice(sliceStart)
return current.length > 0 ? current : index
}
function isActive(route) {
return get() === route
}
function listen(listener) {
listeners.push(listener)
}
function notifyListeners(location, action) {
listeners.forEach(listener => listener(get()))
}
history.listen(notifyListeners)
return {
go,
get,
back: history.goBack,
forward: history.goForward,
isActive,
listen
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment