Basic Routing
React router
First thing he missed when working with React was Ember’s router which is “amazing”.
He started to add Ember’s routers best features then Michael Jackson a friend of Ryan stepped in to help and they created React router: https://github.com/reactjs/react-router
It then became the de facto router for React.
What is routing
It’s just data. If we have an App and a
render
method, I can give it a route.
var React = require('react');
var App = React.createClass({
render () {
return {
<div>{this.props.route}</div>
}
}
});
React.render(<App route={loaction.href.substr(0)}/>, document.body);
This will render the page location (URL). You can also just get the hash:
<App route={loaction.hash.substr(1)}/>
var React = require('react');
var App = React.createClass({
render () {
return {
<div>{this.props.route}</div>
}
}
});
// 2. render once, when the app starts
var render = () => {
React.render(<App route={loaction.href.substr(0)}/>, document.body);
}
// 1. ++++ add EventListener
window.addEventListener('onhashchange', render)
render();
to demonstrate it works let’s add some links that change the hash:
var React = require('react');
var App = React.createClass({
render () {
return {
<div>
// 1. add the links
// add {' '} to force JSX to add some whitespace between the two elements
<a href="#/foo">Foo</a> {' '}
<a href="#/bar">Bar</a>
<p>{this.props.route}</p>
</div>
}
}
});
var render = () => {
React.render(<App route={loaction.href.substr(0)}/>, document.body);
}
// 2. correct the eventName (hashchange and not onhashchange)
window.addEventListener('hashchange', render)
render();
This is a working routing. Just data, again, that moves. To decide for example which page to show:
var React = require('react');
var App = React.createClass({
render () {
// 1. ++++ add page logic
var pages = {
'foo': <div>Foo</div>,
'bar': <div>Bar</div>
};
var page = page[this.props.route];
return {
<div>
<a href="#foo">Foo</a> {' '}
<a href="#bar">Bar</a>
// 2. ++++ include the `page`
{page}
</div>
}
}
});
var render = () => {
React.render(<App route={loaction.href.substr(0)}/>, document.body);
}
window.addEventListener('hashchange', render)
render();
Routing can be as simple as this. Just pass the route info to your app and react to it.