Created
February 20, 2015 22:44
-
-
Save asbjornenge/856a099da18e9224c871 to your computer and use it in GitHub Desktop.
Tiny React 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 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 | |
) |
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 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