react-crossroads
Version:
Client side router for web applications built with React and utilizing the Flux architecture. The backing routing engine is CrossroadsJs.
72 lines (63 loc) • 1.99 kB
JavaScript
var Dispatcher, Logger, NamedLocations, React, Router, RouterContext, Routes;
React = require('react');
NamedLocations = require('../locations/NamedLocations');
Routes = require('./Routes');
RouterContext = require('../context/RouterContext');
Logger = require('../utils/logger');
Dispatcher = require('flux').Dispatcher;
Router = React.createClass({
displayName: 'Router',
getDefaultProps: function() {
return {
location: 'hash',
initialPath: ''
};
},
childContextTypes: {
router: React.PropTypes.object.isRequired
},
contextTypes: {
dispatcher: React.PropTypes.object
},
getChildContext: function() {
return {
router: this.state.routerContext
};
},
getInitialState: function() {
var dispatcher, routerContext;
dispatcher = this.props.dispatcher || this.context.dispatcher || new Dispatcher();
routerContext = new RouterContext(dispatcher);
React.createElement(Routes, {
"path": '/'
}, this.props.children).register([], '', routerContext.stores.route);
return {
routesRegistered: true,
routerContext: routerContext
};
},
propTypes: {
location: React.PropTypes.string.isRequired,
initialPath: React.PropTypes.string.isRequired
},
componentWillMount: function() {
var location;
location = NamedLocations.locationFor(this.props.location);
this.state.routerContext.stores.location.setup(location, this.props.initialPath);
this.state.routerContext.stores.route.addChangeListener(this.routeChanged);
return this.state.routerContext.stores.route.start();
},
routeChanged: function() {
return this.setState({
currentChain: this.state.routerContext.stores.route.getCurrentChain()
});
},
render: function() {
Logger.debug.log('Rendering active chain');
if (this.state.currentChain == null) {
return null;
}
return React.createElement(this.state.currentChain.render, null);
}
});
module.exports = Router;