Last Updated: February 25, 2016
·
1.875K
· sydcanem

Simple router mixin for React

var RouterMixin = {
  respondTo: function(routes, root, pushState) {
    var self = this;

    if (!router) {
      router = new Backbone.Router();
    }

    for (var route in routes) {
      var name = 'route' + routeId++;
      router.route(route, name, routes[route].bind(self));
    }

    if (!started) {
      pushState = !!pushState;
      Backbone.history.start({ root: root || '/', pushState: pushState });
      started = true;
    }
  }
};

Example:

React.createClass({
  mixin: [Router],
  componentDidMount: function() {
    this.respondTo({
      '': this.fetchData,
      'features/:id': this.fetchFeature
    });
  },
  fetchData: function() {
    ...
  },
  fetchFeature: function(id) {
    ...
  }
});

Credits:

https://gist.github.com/darthapo/7165970