Skip to content

Instantly share code, notes, and snippets.

@alicia
Created July 26, 2015 18:22
Show Gist options
  • Save alicia/8012828087547bd2d7ca to your computer and use it in GitHub Desktop.
Save alicia/8012828087547bd2d7ca to your computer and use it in GitHub Desktop.
routing example for single page app using React and Reflux
var ChangeRoute = Reflux.createAction();
var Route = Reflux.createStore({
init: function() {
this.listenTo(ChangeRoute, this.onChangeRoute);
},
onChangeRoute: function(route) {
window.history.pushState(null, null, route);
this.trigger(route);
}
});
var About = React.createClass({
render: function() {
return (
<h2>About</h2>
);
}
});
var Home = React.createClass({
render: function() {
return (
<h2>Home</h2>
);
}
});
var Inbox = React.createClass({
render: function() {
return (
<h2>Inbox</h2>
);
}
});
var RouteLink = React.createClass({
propTypes: {
children: React.PropTypes.element.isRequired,
route: React.PropTypes.string.isRequired
},
handleRouteChange: function(e) {
e.preventDefault();
ChangeRoute(this.props.route);
},
render: function() {
return (
<a href={this.props.route} onClick={this.handleRouteChange}>
{this.props.children}
</a>
)
}
});
var App = React.createClass({
mixins: [Reflux.ListenerMixin],
getInitialState: function() {
return {route: window.location.pathname};
},
componentDidMount: function() {
this.listenTo(Route, this.onRouteUpdate);
window.addEventListener('popstate', this.onPopState);
},
componentWillUnmount: function() {
window.removeEventListener('popstate', this.onPopState);
},
onPopState: function() {
this.setState({ route: window.location.pathname });
},
onRouteUpdate: function(route) {
this.setState({ route: route });
},
render: function() {
var Page;
switch (this.state.route) {
case '/about': Page = About; break;
case '/inbox': Page = Inbox; break;
default: Page = Home;
}
return (
<div>
<h2>Menu</h2>
<ul>
<li>
<RouteLink route='/about'>About</RouteLink>
</li>
<li>
<RouteLink route='/inbox'>Inbox</RouteLink>
</li>
</ul>
<Page/>
</div>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment