Skip to content

Instantly share code, notes, and snippets.

@vcarel
Last active August 29, 2015 14:12
Show Gist options
  • Save vcarel/294992448514f7b0cc47 to your computer and use it in GitHub Desktop.
Save vcarel/294992448514f7b0cc47 to your computer and use it in GitHub Desktop.
"use strict";
var history = window.history;
var routes = {};
var defaultCallback;
function applyRoutes() {
var callback = routes[document.location.pathname];
if (callback) {
callback();
} else if (defaultCallback) {
defaultCallback();
}
}
module.exports = {
route: function (path, callback) {
routes[path] = callback;
},
defaultRoute: function (callback) {
defaultCallback = callback;
},
navigate: function (path) {
if (path !== document.location.pathname) {
history.pushState({}, 'route: ' + path, path);
applyRoutes();
}
},
replace: function (path) {
if (path !== document.location.pathname) {
history.replaceState({}, 'route: ' + path, path);
applyRoutes();
}
},
start: function () {
window.onpopstate = function () {
applyRoutes();
};
applyRoutes();
}
};
module.exports = React.createClass({
componentDidMount: function () {
var self = this;
router.route('/', function (ctx) {
self.setState({ currentPage: {name: 'default', body: <div>default page</div>}});
});
router.route('/foo', function () {
self.setState({ currentPage: {name: 'foo', body: <div>foo page</div>}});
});
router.route('/bar', function () {
self.setState({ currentPage: {name: 'bar', body: <div>bar page</div>}});
});
router.defaultRoute(function () {
router.replace('/');
});
router.start();
},
getInitialState: function () {
return { currentPage: {name: 'default', body: <div>default page</div>}};
},
render: function () {
return (
<div>
<nav>
<ul>
<li><a className={this.state.currentPage.name === 'default' ? 'active' : ''} href="/">default page</a></li>
<li><a className={this.state.currentPage.name === 'foo' ? 'active' : ''} href="/foo">foo</a></li>
<li><a className={this.state.currentPage.name === 'bar' ? 'active' : ''} href="/bar">bar</a></li>
<li><a className={this.state.currentPage.name === 'anything' ? 'active' : ''} href="/anything">anything is routed to default page</a></li>
</ul>
</nav>
<main>
{ this.state.currentPage.body }
</main>
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment