Skip to content

Instantly share code, notes, and snippets.

@asbjornenge
Created February 20, 2015 22:44
Show Gist options
  • Save asbjornenge/856a099da18e9224c871 to your computer and use it in GitHub Desktop.
Save asbjornenge/856a099da18e9224c871 to your computer and use it in GitHub Desktop.
Tiny React Router
import React from 'react'
import Router from './Router'
import Home from './components/Home'
import Blog from './components/Blog'
let routes = {
'/' : Home,
'/blog/:id' : Blog
}
React.render(
<Router routes={routes} />,
document.body
)
import React from 'react'
import assign from 'react/lib/Object.assign'
import Route from 'route-parser'
export default class Router extends React.Component {
constructor(props) {
super(props)
let routes = Object.keys(this.props.routes).map((route) => {
return { route : new Route(route), handler : this.props.routes[route] }
})
this.state = { url : window.location.hash.slice(1), routes : routes }
}
render() {
return this.getComponent()
}
getComponent() {
let url = this.state.url == '' ? '/' : this.state.url
return this.state.routes.reduce((def, route) => {
let props = route.route.match(url)
if (props) return this.createElement(route.handler, props)
return def
},<div>404 not found</div>)
}
createElement(Handler, props) {
return <Handler {...this.props} {...props} />
}
componentDidMount() {
window.onhashchange = () => this.setState({ url : window.location.hash.slice(1) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment