Skip to content

Instantly share code, notes, and snippets.

@nhusher
Created September 7, 2016 19:00
Show Gist options
  • Save nhusher/96ddcdd9fc3f2da0518e36c8eae77659 to your computer and use it in GitHub Desktop.
Save nhusher/96ddcdd9fc3f2da0518e36c8eae77659 to your computer and use it in GitHub Desktop.
import React from 'react'
// TODO: warn when using this, because it's high-test enriched technical debt:
export class TinyNavigator extends React.Component {
constructor (...args) {
super(...args)
this.state = {
path: this.checkPath()
}
this.handleHistoryChange = () => {
this.setState({
path: this.checkPath()
})
}
this.navigate = path => {
let { root } = this.props
if(path) {
history.pushState(null, null, `${root}/${path[0] === '/' ? path.slice(1) : path}`)
} else {
history.pushState(null, null, root)
}
this.setState({
path: this.checkPath()
})
}
}
componentDidMount () {
window.addEventListener('popstate', this.handleHistoryChange)
}
componentWillUnmount () {
window.removeEventListener('popstate', this.handleHistoryChange)
}
checkPath () {
let
path = window.location.pathname,
regex = new RegExp(`${this.props.root}(\/.+)`)
return regex.test(path) ? regex.exec(path)[1].slice(1) : null
}
render () {
let
{ path } = this.state,
navigate = this.navigate,
renderedChildren = this.props.children({ navigate, path })
return renderedChildren && React.Children.only(renderedChildren)
}
}
TinyNavigator.propTypes = {
root: React.PropTypes.string,
children: React.PropTypes.func
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment