3

I'm using React Router for server side rendering and I'd like to run a special action on certain Route, actually on DefaultRoute. How should I create condition for that? I tried following code:

var React = require("react");
var Router = require("react-router");

var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;

var routes = [
    React.createElement(Route, {name: "root", path: "/", handler: Root},
        React.createElement(DefaultRoute, {handler: Default})
    )
]

var Default = React.createClass({
    displayName: "Default",
    render: function () {
        return React.createElement("h2", null, "Default");
    }
});

var Root = React.createClass({
    displayName: "App",
    render: function () {
        return (
            React.createElement(RouteHandler, null)
        );
    }
});

app.get('*', function (req, res) {
    Router.run(routes, req.path, function (Root, state) {
        if (React.createElement(Root, null).constructor.displayName === 'Default'){
            //run specific action
        }   
    });
}); 

But I can't get the name of component this way. Is there any other way to recognize that I'm on Default Route??

laser
  • 1,378
  • 13
  • 13
Ladislav M
  • 2,067
  • 4
  • 29
  • 51

2 Answers2

1

I'm also using React-Router for isomorphic server side routing.

The state prop in the callback of Router.run contains the active routes. You could do something like:

// states.routes returns the nested routes that your path matches.
// This will return the last route. 
if (state.routes[state.routes.length-1].isDefault) {
  // stuff here
  // you also have access to the onEnter method and the handler (component) in the route too.
}

Check out the API documentation here: http://rackt.github.io/react-router/#Router.run. Good luck!

BradByte
  • 10,278
  • 2
  • 33
  • 41
0
if (state.routes.length === 0 || state.routes[state.routes.length - 1].isDefault) { 
    // stuff here 
}

That's even better.

Ladislav M
  • 2,067
  • 4
  • 29
  • 51