Last Updated: February 25, 2016
·
2.298K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

A React app still loads third-party scripts outside the component tree. Tag managers, analytics, and payment fields can read the DOM those components render.

Security insights from Cside